aboutsummaryrefslogblamecommitdiff
path: root/pkcs11-helper.c
blob: 111dbdb3647bc2af06f77ffe83bc7e762703b701 (plain) (tree)
1
2
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
  
                                                               



































                                                                               
                                  
 
















                                                                       


                                                               
 


































                                                                                                                               
                                             
        

   














































































































































































































































































                                                                                


                           
                                                                                  
                                       



                                                                                 
















                                             

      





                                            

      
     


                                            


      





                                               


      


                                                 


      

                                               


      


                                               


      

                                          


      

                                           

                                     


      
                        
                                               
                                       
                                
                                
                                             



                          
                                          



                
                                           


                                          



                 
                                          
  
 
      





                                       
  
 
      



                                         
  
 
      





                                          

  




















                                                                          

      





                                                    
  
      





                                                

      


                                                           
  
      


                                                  

      


                                                      

      



                                                  
      



























                                                                
 



                                                                          

      













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                                                    
 






                                                                                     
        



























                                                                        
         






                                                         

 





                                                   
                                         
                                           
   


















                                                                                                                                                
 


                                   
 










                                                      
 









                                                                                          
 

































































































































































































































































































































































                                                                                                                                                       
 













                                                                                         
                 
         
 





                                                                                     
 

                  
 






                                                   
 


                                                      
 





                                                                                                             
 

                                                                   

                    






                                                                 
                   

                                          
 











                                                                                     


                 









                                                                
         








                                                                                          

 



                                                   
   

                                       
 


                                                      
 




                                                                                                     

          











                                                                 
 






                                                                                     
 






                                                                          
 









                                                                

         




                                                                                  

          
                  

 







                                                                          


      
                                    
                                     
                                                 
   




                                                                                   
                          
 

                                          
 


                                                                                               
                       
                                  

          

                           

                                                   

                                                      

                      









                                                                                    



                           







                                                                                                        

                    
                                                   
                         

                                                           



                                                 

         












                                                                                                 
                   

                                        






                  
                                      
                                     
                                                 
   



                                                           

                          
                                    
 

                                          
 


                                                                                                 
                       
                                  

          






                                                     
           
                                            
                                 
                                      
 
                                                  


                                 




                                                   
                                        










                                                       
                   
                                          
 






                                                                                    
 




                                                                     
 


                                                                          

                                 







































                                                                                                                      


                 



















                                                                                                  

          
                   



      
                                   
                                      
                                                 
   
                                                   
 


                                                           
 
                                    
 





                                                                                               
                        
                                  

          






                                                     
           
                                            
                                 
                                      
 
                                                  


                                 




                                                   
                                        










                                                       
                   
                                           
 





                                                                          
 







                                                                           
 


                                                                          

                                 
 








                                                                                                                       
 





                                               
 







                                                                                              
 




                                       
 



                                                       
 


                                                                  
         


                                         
         







                                                                                           

                  
 


                                                                                                
                   

                                        




                  
     
                      

                                         
                                                 
   


                                          
 




                                                 
 




                                                      
 


                                                                                                  

                           
                                  

          







                                                                                  
         
      
 












                                                                                                                             

         





















                                                                   
 

                                      
                 
 



















                                                                                   
                            



                                                                                
                           
                                                

                         






                                                                     
 


                                         
 



                                       
 



                                                     
 



                                                                     
         
      
 


                                                                                   
                   

                                        




                  
                                                                                        
 
                                       

      




                                           
   



                                         
 


                                             
 


                                         
 


                                                                
 



                                                                  
                                 

                                                                  
                         
 
                            
                 

                    



      
                                         
                                           

                                                             
   







                                                                            

                          
                   
 









                                                                                                                     

          

                                                        

         
                           





                                                                     


                  






























































                                                                                                                

                  
        

                               
                                                        
           
                                                 

         








                                                 
 


                                                                                      








                                       
                                           
                                           

                                                             
   






                                                                           

                          
                   
 






                                                                                                                       
                                

                                       

          
                           
                                                        


                           





                                                                     


                  






                                                         
 







                                                                      
 


                                                  
 
                                           
 








                                                                                       
 
































                                                                                          

                          



























                                                                                                                

         












                                                                                        






                                       
     





                                                             
   





                                                       
 















                                                                                                                                       

          
                                 
 


                                                                 
 






                                                 
 





                                                   
 



                                                  
 







                                                                                          
 

                                                                          
 












                                                                           
                 




                                                                      
                          

                                                         




                                                                        



                                               
 





                                                                             
 






















                                                                                      

                         

         


                                                   

         


                                                           
         
 


                                                  
         
 









                                                                                             
 


































                                                                          
         



                                                         

          
                      

 
     


                                                           
   





                                                     
                          
 


                                                      
 




                                                                             
 
                                
 







                                                                                  
 














                                                             
 
                                   




                                                   

                          
 












                                                                                                               
                         





                                                                          
                         





































































                                                                                              
                                                   


                                                                                       

                                          
 



                                                                       

                                          












                                                                                      
                         
                 
         
 



                                                 
 



                                                        
 



                                                                          
         




                                                                                            
                   

                                        
          
        
                  

 



                                
     

                                                    
   









                                                                         

          


                                               
 






                                                                

         


                                                        




                      




                                                         
   


                                                   
 

                                         
 







                                                                           
          
 
                               
 





                                                   
 



                                                  
 













































































































                                                                                                   
 






















                                                                                             


                           

                                               
         



                                                  

         


                                                      
         



                                                                                         
                   

                                        
          
        


                  




                                                         
     




                                          
 







                                                                                 
          

                                                              
 




                                                                                   
 






                                                                

                 







                                                                             
                 








                                                                         
 






                                                                              
                         








                                                                                            

                         






                                                                           
                         







                                                                                 

                         

                                                                                              
                         













                                                                                     
                         
 



                                                                           
 



                                                                     
 



                                                                      
 








                                                                                                                        
 





                                               
 


                                                         
 










                                                                                               
 





                                                                            
 



                                                   
 





                                                                                   
 
                  

 
      
     



                                                                         
   





                                           
 

                                                                  
 

                           
 

                          


                                                                     
 





                                                                                                                                 

          

                                               
         


                                   

                           































                                                                                                                         
                 
 
         
 
                           
































                                                                                   



                           













































                                                                                              



                           


                                            
 


                                                        
                         
                                                       


                 


                                                               

         


                                                       

         










                                                                             







                                       



                                                           
 


                                                           
 




                                                                               
 




                                                                      
                 

                                           

         


                                                               



                      
 
     




                                                                         
   



                                          

                          













                                                                                                                                              
 



                                               
 







                                                                                 


                               



                                                    
           







                                                                              


                           








                                                           
         













                                                                                  
        































                                                                                                                            
         
                                   
 





                                                                                 
         




























                                                                                      
 
                                   




















































                                                                                                                       
                                  














                                                                  

                         
 












                                                                                              
                 































                                                                                 
                                  
























                                                                                             

                         

         























                                                                             






                                       
                                                                
 
                                                         
 



                                                                          
 











                                         

 



                             
   

                                                            
                          
 



                                                                           

          

                                                   

         




                                                                                          

                  

                                                         
                   








                                                                                              
                    


























                                                                                                 
                 
         
 














                                                                             
                          

                                                                             
                 



                                                 
 













                                                                        

                          















































                                                                                                      
 




                                                                                                     
 





                                                                                  



                         



                                                                            
          

                    

 



                            
   
                                   
 
                
 


                                                           

          








                                                                               
 






                                                                                 

                  



                                                     
                   



                                                                     
                   













                                                                                                 

                 









                                                                                          
                          
                                                                    
                 



                                                                 
                          
                                                                                               
                 
         
 

                                                    
 












                                                                                         



                         


                                                            

          
                    

 
      
     
                            
                          
 


                                                        

          
                                                     
                                   
                                                                                
                 
                
                                   



                                                                 
                          
                 
                
                                   
                                                                     


                 


                                                                      






                                       
      
     
                              
        


                                                          

          


                                                                     

         



                                                           
 





                                 
        











                                                                               
                 


                                                                   

         


                                                              




                      
      
 



                                                                          


                         
                                      



                                          
                                   


                                                                           
                                                                    
      
                                       




                       

                                          

                             
                                                                                       
        

                                                    
 
                                    

 










                                        

      
                      





                                     
      


                                    
 

                                   
                                                                                                      






                            

                                  
                                                                  

          

                                   
                                                      
          

                  

 











                                        









                                  
      
                                                                                           




                                        
                                  
                        
 


                                      
 

                                   








                                                                                                                   



                                         






                                                 






                                         
                                                                                    
                   
                                        


                                   
                                           



                                       
                                                                           











                                                         

                                                     
        
                                                          
 


                                                              



                                       
                                                               



                                                 
                                   

                                                

                 





                                                             

         
                           

                                           

                                                       
 












                                                                                                                                  



                                
                                                   

         

                                   




                                                                      







                                      
                                                                                               
 

                                   





                                                                    

                                                   

















                                                                      
                                                      
 

                                   






                                                           




                                                         
 

                                   
                                                                



                      


                                                                            
           

                                                                                  


                  
                                                                 
 










                                                                                                 


                   
                                                         

         



                                                                                     

          
                               



                             
                                                          
   

                                                            
        




                                                                                            

          
                                           
        



                                                          
                 


                                                                               

                 
                                                         

         

                                   





                                                               
                                                          





                                
                                         
                                
 


                                                        
 



                                                                             





                                            

                                                                                                 

         

                      



                                                                                                                                          

         
                                                                                        

                      
                                                                                                 
           

                                                                                             





                                                         

                                                                                 





                                            

                                                                                        





                                                          

                                                                              

         
                  
 


                                                                  



                            
                                   
                                                               
                 
 

                                                                                                                




                  


                                                        
                                                
                                                     





















                                         

                                   








                                                                  
                                                          


                          
                                               
 



                                                                              

          

                                                        

         

                                   






                                                                    





                                                                          










                                                  


                                              









                                                                                                                  











                                                             







                                                                                                                 
                                                             
















                                                                                                                                      
                                                 
                                                            




















                                                                     
                                            
                                 
                                      
                
                    



                                                 
                                        
                                   












                                                                                                                   

                                                      
                          
                                                                              



                                                                                  
                                                                  





                                                                                            
                                                              
                                                                             


                                                                             
                                                                                                            


                                 



                                                       





                             
            

                                             
                                          



                                                
                    


    








































                                                                          









                                                  


                                                   
 




                                              


















                                                                                                                    











                                                             



                                                                                                                 
          


                               
                                                             















                                                                                                                                           
                                               








                                                                              
                                        
                                                   


                                                   
                                                 
                                                            


                                                            
                                        
                                                   


                                                   
                                               
                                                          





















                                                                           

                                                      

                                       










                                                                                                                                                        


                 
                               
                    

                                                            


                                        
                                                                                                                                                        

                                    
















                                                                                                                                                          
        






























                                                                                                                                                            
                            
                                                              
                                                



                                                                              
                           




                                                                     
                                          














                                                                          
                                            
                                                                              

                                                                   





                                                                                                   

                                                           












                                                                                                                      
                                                  







                                                                                                          
                                                 







                                                                                                                                              
                                                                 


                                                                                                     
                                                                                  
                                                                                          
                                                                  
                                                                                                         

                                                         


                                                                                                         

                                                      


















                                                                                                                  

                                                 

























































































































































































































                                                                                                                                        
                                 
                         










                                                                      
                 


















                                                         




                             

                                                               











                                                                

                                                           
/*
 * Copyright (c) 2005-2006 Alon Bar-Lev <alon.barlev@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modifi-
 * cation, are permitted provided that the following conditions are met:
 *
 *   o  Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *   o  Redistributions in binary form must reproduce the above copyright no-
 *      tice, this list of conditions and the following disclaimer in the do-
 *      cumentation and/or other materials provided with the distribution.
 *
 *   o  The names of the contributors may not be used to endorse or promote
 *      products derived from this software without specific prior written
 *      permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LI-
 * ABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN-
 * TIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEV-
 * ER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABI-
 * LITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * The routines in this file deal with providing private key cryptography
 * using RSA Security Inc. PKCS #11 Cryptographic Token Interface (Cryptoki).
 *
 */

#include "pkcs11-helper-config.h"

#if defined(ENABLE_PKCS11H_HELPER)

#include "pkcs11-helper.h"

/*===========================================
 * Constants
 */

#if OPENSSL_VERSION_NUMBER < 0x00907000L && defined(CRYPTO_LOCK_ENGINE)
# define RSA_get_default_method RSA_get_default_openssl_method
#else
# ifdef HAVE_ENGINE_GET_DEFAULT_RSA
#  include <openssl/engine.h>
#  if OPENSSL_VERSION_NUMBER < 0x0090704fL
#   define BROKEN_OPENSSL_ENGINE
#  endif
# endif
#endif

#define PKCS11H_INVALID_SLOT_ID		((CK_SLOT_ID)-1)
#define PKCS11H_INVALID_SESSION_HANDLE	((CK_SESSION_HANDLE)-1)
#define PKCS11H_INVALID_OBJECT_HANDLE	((CK_OBJECT_HANDLE)-1)

#define PKCS11H_DEFAULT_SLOTEVENT_POLL		5000
#define PKCS11H_DEFAULT_MAX_LOGIN_RETRY		3
#define PKCS11H_DEFAULT_PIN_CACHE_PERIOD	PKCS11H_PIN_CACHE_INFINITE

enum _pkcs11h_private_op_e {
	_pkcs11h_private_op_sign=0,
	_pkcs11h_private_op_sign_recover,
	_pkcs11h_private_op_decrypt
};

/*===========================================
 * Macros
 */

#define PKCS11H_MSG_LEVEL_TEST(flags) (((unsigned int)flags) <= s_pkcs11h_loglevel)

#if defined(HAVE_CPP_VARARG_MACRO_ISO) && !defined(__LCLINT__)
# define PKCS11H_LOG(flags, ...) do { if (PKCS11H_MSG_LEVEL_TEST(flags)) _pkcs11h_log((flags), __VA_ARGS__); } while (FALSE)
# ifdef ENABLE_PKCS11H_DEBUG
#  define PKCS11H_DEBUG(flags, ...) do { if (PKCS11H_MSG_LEVEL_TEST(flags)) _pkcs11h_log((flags), __VA_ARGS__); } while (FALSE)
# else
#  define PKCS11H_DEBUG(flags, ...)
# endif
#elif defined(HAVE_CPP_VARARG_MACRO_GCC) && !defined(__LCLINT__)
# define PKCS11H_LOG(flags, args...) do { if (PKCS11H_MSG_LEVEL_TEST(flags)) _pkcs11h_log((flags), args); } while (FALSE)
# ifdef ENABLE_PKCS11H_DEBUG
#  define PKCS11H_DEBUG(flags, args...) do { if (PKCS11H_MSG_LEVEL_TEST(flags)) _pkcs11h_log((flags), args); } while (FALSE)
# else
#  define PKCS11H_DEBUG(flags, args...)
# endif
#else
# define PKCS11H_LOG _pkcs11h_log
# define PKCS11H_DEBUG _pkcs11h_log
#endif

/*===========================================
 * Types
 */

struct pkcs11h_provider_s;
struct pkcs11h_session_s;
struct pkcs11h_data_s;
typedef struct pkcs11h_provider_s *pkcs11h_provider_t;
typedef struct pkcs11h_session_s *pkcs11h_session_t;
typedef struct pkcs11h_data_s *pkcs11h_data_t;

#if OPENSSL_VERSION_NUMBER < 0x00908000L
typedef unsigned char *pkcs11_openssl_d2i_t;
#else
typedef const unsigned char *pkcs11_openssl_d2i_t;
#endif

#if defined(ENABLE_PKCS11H_THREADING)

#define PKCS11H_COND_INFINITE	0xffffffff

#if defined(WIN32)
#define PKCS11H_THREAD_NULL	NULL
typedef HANDLE pkcs11h_cond_t;
typedef HANDLE pkcs11h_mutex_t;
typedef HANDLE pkcs11h_thread_t;
#else
#define PKCS11H_THREAD_NULL	0l
typedef pthread_mutex_t pkcs11h_mutex_t;
typedef pthread_t pkcs11h_thread_t;

typedef struct {
	pthread_cond_t cond;
	pthread_mutex_t mut;
} pkcs11h_cond_t;

typedef struct __pkcs11h_mutex_entry_s {
	struct __pkcs11h_mutex_entry_s *next;
	pkcs11h_mutex_t *p_mutex;
	PKCS11H_BOOL fLocked;
} *__pkcs11h_mutex_entry_t;
#endif

typedef void * (*pkcs11h_thread_start_t)(void *);

typedef struct {
	pkcs11h_thread_start_t start;
	void *data;
} __pkcs11h_thread_data_t;

#endif				/* ENABLE_PKCS11H_THREADING */

struct pkcs11h_provider_s {
	pkcs11h_provider_t next;

	PKCS11H_BOOL fEnabled;
	char szReferenceName[1024];
	char manufacturerID[sizeof (((CK_TOKEN_INFO *)NULL)->manufacturerID)+1];
	
#if defined(WIN32)
	HANDLE hLibrary;
#else
	void *hLibrary;
#endif

	CK_FUNCTION_LIST_PTR f;
	PKCS11H_BOOL fShouldFinalize;
	PKCS11H_BOOL fProtectedAuthentication;
	PKCS11H_BOOL fCertIsPrivate;
	unsigned maskSignMode;
	int nSlotEventMethod;
	int nSlotEventPollInterval;

#if defined(ENABLE_PKCS11H_SLOTEVENT)
	pkcs11h_thread_t threadSlotEvent;
#endif
};

struct pkcs11h_session_s {
	pkcs11h_session_t next;

	int nReferenceCount;
	PKCS11H_BOOL fValid;

	pkcs11h_provider_t provider;

	pkcs11h_token_id_t token_id;

	CK_SESSION_HANDLE hSession;

	PKCS11H_BOOL fProtectedAuthenticationSupported;
	int nPINCachePeriod;
	time_t timePINExpire;

#if defined(ENABLE_PKCS11H_ENUM)
#if defined(ENABLE_PKCS11H_CERTIFICATE)
	pkcs11h_certificate_id_list_t cached_certs;
	PKCS11H_BOOL fTouch;
#endif
#endif

#if defined(ENABLE_PKCS11H_THREADING)
	pkcs11h_mutex_t mutexSession;
#endif
};

#if defined (ENABLE_PKCS11H_CERTIFICATE)

struct pkcs11h_certificate_s {

	pkcs11h_certificate_id_t id;
	int nPINCachePeriod;

	unsigned maskSignMode;

	pkcs11h_session_t session;
	CK_OBJECT_HANDLE hKey;

	PKCS11H_BOOL fOperationActive;

#if defined(ENABLE_PKCS11H_THREADING)
	pkcs11h_mutex_t mutexCertificate;
#endif
};

#endif				/* ENABLE_PKCS11H_CERTIFICATE */

struct pkcs11h_data_s {
	PKCS11H_BOOL fInitialized;
	int nPINCachePeriod;

	pkcs11h_provider_t providers;
	pkcs11h_session_t sessions;

	struct {
		void *log_data;
		void *slotevent_data;
		void *token_prompt_data;
		void *pin_prompt_data;
		pkcs11h_hook_log_t log;
		pkcs11h_hook_slotevent_t slotevent;
		pkcs11h_hook_token_prompt_t token_prompt;
		pkcs11h_hook_pin_prompt_t pin_prompt;
	} hooks;

	PKCS11H_BOOL fProtectedAuthentication;
	int nMaxLoginRetries;

#if defined(ENABLE_PKCS11H_THREADING)
	pkcs11h_mutex_t mutexGlobal;
	pkcs11h_mutex_t mutexSession;
	pkcs11h_mutex_t mutexCache;
#endif

#if defined(ENABLE_PKCS11H_SLOTEVENT)
	PKCS11H_BOOL fSlotEventInitialized;
	PKCS11H_BOOL fSlotEventShouldTerminate;
	PKCS11H_BOOL fSlotEventSkipEvent;
	pkcs11h_cond_t condSlotEvent;
	pkcs11h_thread_t threadSlotEvent;
#endif
};

#if defined(ENABLE_PKCS11H_OPENSSL)
struct pkcs11h_openssl_session_s {
	int nReferenceCount;
	PKCS11H_BOOL fInitialized;
	X509 *x509;
	RSA_METHOD smart_rsa;
	int (*orig_finish)(RSA *rsa);
	pkcs11h_certificate_t certificate;
};
#endif

/*======================================================================*
 * MEMORY INTERFACE
 *======================================================================*/

static
CK_RV
_pkcs11h_malloc (
	OUT const void ** const p,
	IN const size_t s
);
static
CK_RV
_pkcs11h_free (
	IN const void ** const p
);
static
CK_RV
_pkcs11h_dupmem (
	OUT const void ** const dest,
	OUT size_t * const dest_size,
	IN const void * const src,
	IN const size_t mem_size
);

#if defined(ENABLE_PKCS11H_THREADING)
/*======================================================================*
 * THREADING INTERFACE
 *======================================================================*/

static
void
_pkcs11h_sleep (
	IN const unsigned milli
);
static
CK_RV
_pkcs11h_mutexInit (
	OUT pkcs11h_mutex_t * const mutex
);
static
CK_RV
_pkcs11h_mutexLock (
	IN OUT pkcs11h_mutex_t *const mutex
);
static
CK_RV
_pkcs11h_mutexRelease (
	IN OUT pkcs11h_mutex_t *const mutex
);
static
CK_RV
_pkcs11h_mutexFree (
	IN OUT pkcs11h_mutex_t *const mutex
);
#if !defined(WIN32)
static
void
__pkcs1h_mutexLockAll ();
static
void
__pkcs1h_mutexReleaseAll ();
#endif
static
CK_RV
_pkcs11h_condSignal (
	IN OUT pkcs11h_cond_t *const cond
);
static
CK_RV
_pkcs11h_condInit (
	OUT pkcs11h_cond_t * const cond
);
static
CK_RV
_pkcs11h_condWait (
	IN OUT pkcs11h_cond_t *const cond,
	IN const unsigned milli
);
static
CK_RV
_pkcs11h_condFree (
	IN OUT pkcs11h_cond_t *const cond
);
static
CK_RV
_pkcs11h_threadStart (
	OUT pkcs11h_thread_t * const thread,
	IN pkcs11h_thread_start_t const start,
	IN void * data
);
static
CK_RV
_pkcs11h_threadJoin (
	IN pkcs11h_thread_t * const thread
);
#endif				/* ENABLE_PKCS11H_THREADING */

/*======================================================================*
 * COMMON INTERNAL INTERFACE
 *======================================================================*/

static
void
_pkcs11h_fixupFixedString (
	OUT char * const szTarget,			/* MUST BE >= nLength+1 */
	IN const char * const szSource,
	IN const size_t nLength				/* FIXED STRING LENGTH */
);
static
void
_pkcs11h_log (
	IN const unsigned flags,
	IN const char * const szFormat,
	IN ...
)
#ifdef __GNUC__
    __attribute__ ((format (printf, 2, 3)))
#endif
    ;

static
CK_RV
_pkcs11h_getSlotList (
	IN const pkcs11h_provider_t provider,
	IN const CK_BBOOL tokenPresent,
	OUT CK_SLOT_ID_PTR * const pSlotList,
	OUT CK_ULONG_PTR pulCount
);
static
CK_RV
_pkcs11h_getObjectAttributes (
	IN const pkcs11h_session_t session,
	IN const CK_OBJECT_HANDLE object,
	IN OUT const CK_ATTRIBUTE_PTR attrs,
	IN const unsigned count
);
static
CK_RV
_pkcs11h_freeObjectAttributes (
	IN OUT const CK_ATTRIBUTE_PTR attrs,
	IN const unsigned count
);
static
CK_RV
_pkcs11h_findObjects (
	IN const pkcs11h_session_t session,
	IN const CK_ATTRIBUTE * const filter,
	IN const CK_ULONG filter_attrs,
	OUT CK_OBJECT_HANDLE **const p_objects,
	OUT CK_ULONG *p_objects_found
);
static
CK_RV
_pkcs11h_getTokenId (
	IN const CK_TOKEN_INFO_PTR info,
	OUT pkcs11h_token_id_t * const p_token_id
);
static
CK_RV
_pkcs11h_newTokenId (
	OUT pkcs11h_token_id_t * const token_id
);
static
CK_RV
_pkcs11h_getSessionByTokenId (
	IN const pkcs11h_token_id_t token_id,
	OUT pkcs11h_session_t * const p_session
);
static
CK_RV
_pkcs11h_releaseSession (
	IN const pkcs11h_session_t session
);
static
CK_RV
_pkcs11h_resetSession (
	IN const pkcs11h_session_t session,
	IN const unsigned maskPrompt,
	OUT CK_SLOT_ID * const p_slot
);
static
CK_RV
_pkcs11h_getObjectById (
	IN const pkcs11h_session_t certificate,
	IN const CK_OBJECT_CLASS class,
	IN const CK_BYTE_PTR id,
	IN const size_t id_size,
	OUT CK_OBJECT_HANDLE * const p_handle
);
static
CK_RV
_pkcs11h_validateSession (
	IN const pkcs11h_session_t session
);
static
CK_RV
_pkcs11h_login (
	IN const pkcs11h_session_t session,
	IN const PKCS11H_BOOL fPublicOnly,
	IN const PKCS11H_BOOL fReadOnly,
	IN const unsigned maskPrompt
);
static
CK_RV
_pkcs11h_logout (
	IN const pkcs11h_session_t session
);

static
void
_pkcs11h_hooks_default_log (
	IN const void * pData,
	IN const unsigned flags,
	IN const char * const szFormat,
	IN va_list args
);

static
PKCS11H_BOOL
_pkcs11h_hooks_default_token_prompt (
	IN const void * pData,
	IN const pkcs11h_token_id_t token
);

static
PKCS11H_BOOL
_pkcs11h_hooks_default_pin_prompt (
	IN const void * pData,
	IN const pkcs11h_token_id_t token,
	OUT char * const szPIN,
	IN const size_t nMaxPIN
);

#if !defined(WIN32)
#if defined(ENABLE_PKCS11H_THREADING)
static
void
__pkcs11h_atfork_prepare  ();
static
void
__pkcs11h_atfork_parent ();
static
void
__pkcs11h_atfork_child ();
#endif
static
CK_RV
_pkcs11h_forkFixup ();
#endif

#if defined(ENABLE_PKCS11H_CERTIFICATE)
/*======================================================================*
 * CERTIFICATE INTERFACE
 *======================================================================*/

static
void
_pkcs11h_isBetterCertificate_getExpiration (
	IN const unsigned char * const pCertificate,
	IN const size_t nCertificateSize,
	OUT char * const szNotBefore,
	IN const int nNotBeforeSize
);
static
PKCS11H_BOOL
_pkcs11h_isBetterCertificate (
	IN const unsigned char * const pCurrent,
	IN const size_t nCurrentSize,
	IN const unsigned char * const pNew,
	IN const size_t nNewSize
);
static
CK_RV
_pkcs11h_newCertificateId (
	OUT pkcs11h_certificate_id_t * const certificate_id
);
static
CK_RV
_pkcs11h_loadCertificate (
	IN const pkcs11h_certificate_t certificate
);
static
CK_RV
_pkcs11h_updateCertificateIdDescription (
	IN OUT pkcs11h_certificate_id_t certificate_id
);
static
CK_RV
_pkcs11h_ensureCertificateBlob (
	IN const pkcs11h_certificate_t certificate
);
static
CK_RV
_pkcs11h_getCertificateKeyAttributes (
	IN const pkcs11h_certificate_t certificate
);
static
CK_RV
_pkcs11h_validateCertificateSession (
	IN const pkcs11h_certificate_t certificate
);
static
CK_RV
_pkcs11h_resetCertificateSession (
	IN const pkcs11h_certificate_t certificate,
	IN const PKCS11H_BOOL fPublicOnly,
	IN const unsigned maskPrompt
);
static
CK_RV
_pkcs11h_certificate_private_op (
	IN const pkcs11h_certificate_t certificate,
	IN const enum _pkcs11h_private_op_e op,
	IN const CK_MECHANISM_TYPE mech_type,
	IN const unsigned char * const source,
	IN const size_t source_size,
	OUT unsigned char * const target,
	IN OUT size_t * const p_target_size
);
#endif				/* ENABLE_PKCS11H_CERTIFICATE */

#if defined(ENABLE_PKCS11H_LOCATE)
/*======================================================================*
 * LOCATE INTERFACE
 *======================================================================*/

static
CK_RV
_pkcs11h_locate_getTokenIdBySlotId (
	IN const char * const szSlot,
	OUT pkcs11h_token_id_t * const p_token_id
);
static
CK_RV
_pkcs11h_locate_getTokenIdBySlotName (
	IN const char * const szName,
	OUT pkcs11h_token_id_t * const p_token_id
);
static
CK_RV
_pkcs11h_locate_getTokenIdByLabel (
	IN const char * const szLabel,
	OUT pkcs11h_token_id_t * const p_token_id
);

#if defined(ENABLE_PKCS11H_CERTIFICATE)

static
void
_pkcs11h_locate_hexToBinary (
	OUT unsigned char * const target,
	IN const char * const szSource,
	IN OUT size_t * const p_target_size
);
static
CK_RV
_pkcs11h_locate_getCertificateIdByLabel (
	IN const pkcs11h_session_t session,
	IN OUT const pkcs11h_certificate_id_t certificate_id,
	IN const char * const szLabel
);
static
CK_RV
_pkcs11h_locate_getCertificateIdBySubject (
	IN const pkcs11h_session_t session,
	IN OUT const pkcs11h_certificate_id_t certificate_id,
	IN const char * const szSubject
);

#endif				/* ENABLE_PKCS11H_CERTIFICATE */
#endif				/* ENABLE_PKCS11H_LOCATE */

#if defined(ENABLE_PKCS11H_ENUM)
/*======================================================================*
 * ENUM INTERFACE
 *======================================================================*/

#if defined(ENABLE_PKCS11H_CERTIFICATE)

static
CK_RV
_pkcs11h_enum_getSessionCertificates (
	IN const pkcs11h_session_t session
);
static
CK_RV
_pkcs11h_enum_splitCertificateIdList (
	IN const pkcs11h_certificate_id_list_t cert_id_all,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_issuers_list,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_end_list
);

#endif				/* ENABLE_PKCS11H_CERTIFICATE */

#endif				/* ENABLE_PKCS11H_ENUM */

#if defined(ENABLE_PKCS11H_SLOTEVENT)
/*======================================================================*
 * SLOTEVENT INTERFACE
 *======================================================================*/

static
unsigned long
_pkcs11h_slotevent_checksum (
	IN const unsigned char * const p,
	IN const size_t s
);
static
void *
_pkcs11h_slotevent_provider (
	IN void *p
);
static
void *
_pkcs11h_slotevent_manager (
	IN void *p
);
static
CK_RV
_pkcs11h_slotevent_init ();
static
CK_RV
_pkcs11h_slotevent_notify ();
static
CK_RV
_pkcs11h_slotevent_terminate ();

#endif				/* ENABLE_PKCS11H_SLOTEVENT */

#if defined(ENABLE_PKCS11H_OPENSSL)
/*======================================================================*
 * OPENSSL INTERFACE
 *======================================================================*/

static
int
_pkcs11h_openssl_finish (
	IN OUT RSA *rsa
);
#if OPENSSL_VERSION_NUMBER < 0x00907000L
static
int
_pkcs11h_openssl_dec (
	IN int flen,
	IN unsigned char *from,
	OUT unsigned char *to,
	IN OUT RSA *rsa,
	IN int padding
);
static
int
_pkcs11h_openssl_sign (
	IN int type,
	IN unsigned char *m,
	IN unsigned int m_len,
	OUT unsigned char *sigret,
	OUT unsigned int *siglen,
	IN OUT RSA *rsa
);
#else
static
int
_pkcs11h_openssl_dec (
	IN int flen,
	IN const unsigned char *from,
	OUT unsigned char *to,
	IN OUT RSA *rsa,
	IN int padding
);
static
int
_pkcs11h_openssl_sign (
	IN int type,
	IN const unsigned char *m,
	IN unsigned int m_len,
	OUT unsigned char *sigret,
	OUT unsigned int *siglen,
	IN OUT const RSA *rsa
);
#endif
static
pkcs11h_openssl_session_t
_pkcs11h_openssl_get_openssl_session (
	IN OUT const RSA *rsa
);  
static
pkcs11h_certificate_t
_pkcs11h_openssl_get_pkcs11h_certificate (
	IN OUT const RSA *rsa
);  
#endif				/* ENABLE_PKCS11H_OPENSSL */

/*==========================================
 * Static data
 */

#if defined(ENABLE_PKCS11H_THREADING)
#if !defined(WIN32)
static struct {
	pkcs11h_mutex_t mutex;
	__pkcs11h_mutex_entry_t head;
} __s_pkcs11h_mutex_list = {
	PTHREAD_MUTEX_INITIALIZER,
	NULL
};
#endif
#endif

pkcs11h_data_t s_pkcs11h_data = NULL;
unsigned int s_pkcs11h_loglevel = PKCS11H_LOG_INFO;

/*======================================================================*
 * PUBLIC INTERFACE
 *======================================================================*/

char *
pkcs11h_getMessage (
	IN const int rv
) {
	switch (rv) {
		case CKR_OK: return "CKR_OK";
		case CKR_CANCEL: return "CKR_CANCEL";
		case CKR_HOST_MEMORY: return "CKR_HOST_MEMORY";
		case CKR_SLOT_ID_INVALID: return "CKR_SLOT_ID_INVALID";
		case CKR_GENERAL_ERROR: return "CKR_GENERAL_ERROR";
		case CKR_FUNCTION_FAILED: return "CKR_FUNCTION_FAILED";
		case CKR_ARGUMENTS_BAD: return "CKR_ARGUMENTS_BAD";
		case CKR_NO_EVENT: return "CKR_NO_EVENT";
		case CKR_NEED_TO_CREATE_THREADS: return "CKR_NEED_TO_CREATE_THREADS";
		case CKR_CANT_LOCK: return "CKR_CANT_LOCK";
		case CKR_ATTRIBUTE_READ_ONLY: return "CKR_ATTRIBUTE_READ_ONLY";
		case CKR_ATTRIBUTE_SENSITIVE: return "CKR_ATTRIBUTE_SENSITIVE";
		case CKR_ATTRIBUTE_TYPE_INVALID: return "CKR_ATTRIBUTE_TYPE_INVALID";
		case CKR_ATTRIBUTE_VALUE_INVALID: return "CKR_ATTRIBUTE_VALUE_INVALID";
		case CKR_DATA_INVALID: return "CKR_DATA_INVALID";
		case CKR_DATA_LEN_RANGE: return "CKR_DATA_LEN_RANGE";
		case CKR_DEVICE_ERROR: return "CKR_DEVICE_ERROR";
		case CKR_DEVICE_MEMORY: return "CKR_DEVICE_MEMORY";
		case CKR_DEVICE_REMOVED: return "CKR_DEVICE_REMOVED";
		case CKR_ENCRYPTED_DATA_INVALID: return "CKR_ENCRYPTED_DATA_INVALID";
		case CKR_ENCRYPTED_DATA_LEN_RANGE: return "CKR_ENCRYPTED_DATA_LEN_RANGE";
		case CKR_FUNCTION_CANCELED: return "CKR_FUNCTION_CANCELED";
		case CKR_FUNCTION_NOT_PARALLEL: return "CKR_FUNCTION_NOT_PARALLEL";
		case CKR_FUNCTION_NOT_SUPPORTED: return "CKR_FUNCTION_NOT_SUPPORTED";
		case CKR_KEY_HANDLE_INVALID: return "CKR_KEY_HANDLE_INVALID";
		case CKR_KEY_SIZE_RANGE: return "CKR_KEY_SIZE_RANGE";
		case CKR_KEY_TYPE_INCONSISTENT: return "CKR_KEY_TYPE_INCONSISTENT";
		case CKR_KEY_NOT_NEEDED: return "CKR_KEY_NOT_NEEDED";
		case CKR_KEY_CHANGED: return "CKR_KEY_CHANGED";
		case CKR_KEY_NEEDED: return "CKR_KEY_NEEDED";
		case CKR_KEY_INDIGESTIBLE: return "CKR_KEY_INDIGESTIBLE";
		case CKR_KEY_FUNCTION_NOT_PERMITTED: return "CKR_KEY_FUNCTION_NOT_PERMITTED";
		case CKR_KEY_NOT_WRAPPABLE: return "CKR_KEY_NOT_WRAPPABLE";
		case CKR_KEY_UNEXTRACTABLE: return "CKR_KEY_UNEXTRACTABLE";
		case CKR_MECHANISM_INVALID: return "CKR_MECHANISM_INVALID";
		case CKR_MECHANISM_PARAM_INVALID: return "CKR_MECHANISM_PARAM_INVALID";
		case CKR_OBJECT_HANDLE_INVALID: return "CKR_OBJECT_HANDLE_INVALID";
		case CKR_OPERATION_ACTIVE: return "CKR_OPERATION_ACTIVE";
		case CKR_OPERATION_NOT_INITIALIZED: return "CKR_OPERATION_NOT_INITIALIZED";
		case CKR_PIN_INCORRECT: return "CKR_PIN_INCORRECT";
		case CKR_PIN_INVALID: return "CKR_PIN_INVALID";
		case CKR_PIN_LEN_RANGE: return "CKR_PIN_LEN_RANGE";
		case CKR_PIN_EXPIRED: return "CKR_PIN_EXPIRED";
		case CKR_PIN_LOCKED: return "CKR_PIN_LOCKED";
		case CKR_SESSION_CLOSED: return "CKR_SESSION_CLOSED";
		case CKR_SESSION_COUNT: return "CKR_SESSION_COUNT";
		case CKR_SESSION_HANDLE_INVALID: return "CKR_SESSION_HANDLE_INVALID";
		case CKR_SESSION_PARALLEL_NOT_SUPPORTED: return "CKR_SESSION_PARALLEL_NOT_SUPPORTED";
		case CKR_SESSION_READ_ONLY: return "CKR_SESSION_READ_ONLY";
		case CKR_SESSION_EXISTS: return "CKR_SESSION_EXISTS";
		case CKR_SESSION_READ_ONLY_EXISTS: return "CKR_SESSION_READ_ONLY_EXISTS";
		case CKR_SESSION_READ_WRITE_SO_EXISTS: return "CKR_SESSION_READ_WRITE_SO_EXISTS";
		case CKR_SIGNATURE_INVALID: return "CKR_SIGNATURE_INVALID";
		case CKR_SIGNATURE_LEN_RANGE: return "CKR_SIGNATURE_LEN_RANGE";
		case CKR_TEMPLATE_INCOMPLETE: return "CKR_TEMPLATE_INCOMPLETE";
		case CKR_TEMPLATE_INCONSISTENT: return "CKR_TEMPLATE_INCONSISTENT";
		case CKR_TOKEN_NOT_PRESENT: return "CKR_TOKEN_NOT_PRESENT";
		case CKR_TOKEN_NOT_RECOGNIZED: return "CKR_TOKEN_NOT_RECOGNIZED";
		case CKR_TOKEN_WRITE_PROTECTED: return "CKR_TOKEN_WRITE_PROTECTED";
		case CKR_UNWRAPPING_KEY_HANDLE_INVALID: return "CKR_UNWRAPPING_KEY_HANDLE_INVALID";
		case CKR_UNWRAPPING_KEY_SIZE_RANGE: return "CKR_UNWRAPPING_KEY_SIZE_RANGE";
		case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: return "CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT";
		case CKR_USER_ALREADY_LOGGED_IN: return "CKR_USER_ALREADY_LOGGED_IN";
		case CKR_USER_NOT_LOGGED_IN: return "CKR_USER_NOT_LOGGED_IN";
		case CKR_USER_PIN_NOT_INITIALIZED: return "CKR_USER_PIN_NOT_INITIALIZED";
		case CKR_USER_TYPE_INVALID: return "CKR_USER_TYPE_INVALID";
		case CKR_USER_ANOTHER_ALREADY_LOGGED_IN: return "CKR_USER_ANOTHER_ALREADY_LOGGED_IN";
		case CKR_USER_TOO_MANY_TYPES: return "CKR_USER_TOO_MANY_TYPES";
		case CKR_WRAPPED_KEY_INVALID: return "CKR_WRAPPED_KEY_INVALID";
		case CKR_WRAPPED_KEY_LEN_RANGE: return "CKR_WRAPPED_KEY_LEN_RANGE";
		case CKR_WRAPPING_KEY_HANDLE_INVALID: return "CKR_WRAPPING_KEY_HANDLE_INVALID";
		case CKR_WRAPPING_KEY_SIZE_RANGE: return "CKR_WRAPPING_KEY_SIZE_RANGE";
		case CKR_WRAPPING_KEY_TYPE_INCONSISTENT: return "CKR_WRAPPING_KEY_TYPE_INCONSISTENT";
		case CKR_RANDOM_SEED_NOT_SUPPORTED: return "CKR_RANDOM_SEED_NOT_SUPPORTED";
		case CKR_RANDOM_NO_RNG: return "CKR_RANDOM_NO_RNG";
		case CKR_DOMAIN_PARAMS_INVALID: return "CKR_DOMAIN_PARAMS_INVALID";
		case CKR_BUFFER_TOO_SMALL: return "CKR_BUFFER_TOO_SMALL";
		case CKR_SAVED_STATE_INVALID: return "CKR_SAVED_STATE_INVALID";
		case CKR_INFORMATION_SENSITIVE: return "CKR_INFORMATION_SENSITIVE";
		case CKR_STATE_UNSAVEABLE: return "CKR_STATE_UNSAVEABLE";
		case CKR_CRYPTOKI_NOT_INITIALIZED: return "CKR_CRYPTOKI_NOT_INITIALIZED";
		case CKR_CRYPTOKI_ALREADY_INITIALIZED: return "CKR_CRYPTOKI_ALREADY_INITIALIZED";
		case CKR_MUTEX_BAD: return "CKR_MUTEX_BAD";
		case CKR_MUTEX_NOT_LOCKED: return "CKR_MUTEX_NOT_LOCKED";
		case CKR_FUNCTION_REJECTED: return "CKR_FUNCTION_REJECTED";
		case CKR_VENDOR_DEFINED: return "CKR_VENDOR_DEFINED";
		default: return "Unknown PKCS#11 error";
	}
}

CK_RV
pkcs11h_initialize () {

#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	CK_RV rv = CKR_OK;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_initialize entry"
	);

	pkcs11h_terminate ();

	if (rv == CKR_OK) {
		rv = _pkcs11h_malloc ((void*)&s_pkcs11h_data, sizeof (struct pkcs11h_data_s));
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (rv == CKR_OK) {
		rv = _pkcs11h_mutexInit (&s_pkcs11h_data->mutexGlobal); 
	}
	if (rv == CKR_OK) {
		rv = _pkcs11h_mutexInit (&s_pkcs11h_data->mutexSession); 
	}
	if (rv == CKR_OK) {
		rv = _pkcs11h_mutexInit (&s_pkcs11h_data->mutexCache); 
	}
#if !defined(WIN32)
	if (
		rv == CKR_OK &&
		pthread_atfork (
			__pkcs11h_atfork_prepare,
			__pkcs11h_atfork_parent,
			__pkcs11h_atfork_child
		)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#endif
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (rv == CKR_OK) {
		s_pkcs11h_data->nMaxLoginRetries = PKCS11H_DEFAULT_MAX_LOGIN_RETRY;
		s_pkcs11h_data->fProtectedAuthentication = TRUE;
		s_pkcs11h_data->nPINCachePeriod = PKCS11H_DEFAULT_PIN_CACHE_PERIOD;
		s_pkcs11h_data->fInitialized = TRUE;
	}

	if (rv == CKR_OK) {
		pkcs11h_setLogHook (_pkcs11h_hooks_default_log, NULL);
		pkcs11h_setTokenPromptHook (_pkcs11h_hooks_default_token_prompt, NULL);
		pkcs11h_setPINPromptHook (_pkcs11h_hooks_default_pin_prompt, NULL);
	}
	
#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_initialize return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_terminate () {

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_terminate entry"
	);

	if (s_pkcs11h_data != NULL) {
		pkcs11h_provider_t current_provider = NULL;

		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Removing providers"
		);

		for (
			current_provider = s_pkcs11h_data->providers;
			current_provider != NULL;
			current_provider = current_provider->next
		) {
			pkcs11h_removeProvider (current_provider->szReferenceName);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		_pkcs11h_mutexLock (&s_pkcs11h_data->mutexCache);
		_pkcs11h_mutexLock (&s_pkcs11h_data->mutexSession);
		_pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal);
#endif

		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Releasing sessions"
		);

		while (s_pkcs11h_data->sessions != NULL) {
			pkcs11h_session_t current = s_pkcs11h_data->sessions;
			s_pkcs11h_data->sessions = s_pkcs11h_data->sessions->next;

#if defined(ENABLE_PKCS11H_THREADING)
			_pkcs11h_mutexLock (&current->mutexSession);
#endif

			current->fValid = FALSE;

			if (current->nReferenceCount != 0) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Warning: Found session with references"
				);
			}

			if (current->token_id != NULL) {
				pkcs11h_freeTokenId (current->token_id);
				current->token_id = NULL;
			}

#if defined(ENABLE_PKCS11H_ENUM)
#if defined(ENABLE_PKCS11H_CERTIFICATE)
			pkcs11h_freeCertificateIdList (current->cached_certs);
#endif
#endif

			current->provider = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
			_pkcs11h_mutexFree (&current->mutexSession);
#endif

			_pkcs11h_free ((void *)&current);
		}

#if defined(ENABLE_PKCS11H_SLOTEVENT)
		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Terminating slotevent"
		);

		_pkcs11h_slotevent_terminate ();
#endif
		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Marking as uninitialized"
		);
		
		s_pkcs11h_data->fInitialized = FALSE;

		while (s_pkcs11h_data->providers != NULL) {
			pkcs11h_provider_t current = s_pkcs11h_data->providers;
			s_pkcs11h_data->providers = s_pkcs11h_data->providers->next;

			_pkcs11h_free ((void *)&current);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		_pkcs11h_mutexFree (&s_pkcs11h_data->mutexCache);
		_pkcs11h_mutexFree (&s_pkcs11h_data->mutexGlobal); 
		_pkcs11h_mutexFree (&s_pkcs11h_data->mutexSession); 
#endif

		_pkcs11h_free ((void *)&s_pkcs11h_data);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_terminate return"
	);

	return CKR_OK;
}

void
pkcs11h_setLogLevel (
	IN const unsigned flags
) {
	s_pkcs11h_loglevel = flags;
}

unsigned
pkcs11h_getLogLevel () {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);

	return s_pkcs11h_loglevel;
}

CK_RV
pkcs11h_setLogHook (
	IN const pkcs11h_hook_log_t hook,
	IN void * const pData
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (hook!=NULL);

	s_pkcs11h_data->hooks.log = hook;
	s_pkcs11h_data->hooks.log_data = pData;

	return CKR_OK;
}

CK_RV
pkcs11h_setSlotEventHook (
	IN const pkcs11h_hook_slotevent_t hook,
	IN void * const pData
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (hook!=NULL);

#if defined(ENABLE_PKCS11H_SLOTEVENT)
	s_pkcs11h_data->hooks.slotevent = hook;
	s_pkcs11h_data->hooks.slotevent_data = pData;

	return _pkcs11h_slotevent_init ();
#else
	return CKR_FUNCTION_NOT_SUPPORTED;
#endif
}

CK_RV
pkcs11h_setPINPromptHook (
	IN const pkcs11h_hook_pin_prompt_t hook,
	IN void * const pData
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (hook!=NULL);

	s_pkcs11h_data->hooks.pin_prompt = hook;
	s_pkcs11h_data->hooks.pin_prompt_data = pData;

	return CKR_OK;
}

CK_RV
pkcs11h_setTokenPromptHook (
	IN const pkcs11h_hook_token_prompt_t hook,
	IN void * const pData
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (hook!=NULL);

	s_pkcs11h_data->hooks.token_prompt = hook;
	s_pkcs11h_data->hooks.token_prompt_data = pData;

	return CKR_OK;
}

CK_RV
pkcs11h_setPINCachePeriod (
	IN const int nPINCachePeriod
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);

	s_pkcs11h_data->nPINCachePeriod = nPINCachePeriod;

	return CKR_OK;
}

CK_RV
pkcs11h_setMaxLoginRetries (
	IN const int nMaxLoginRetries
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);

	s_pkcs11h_data->nMaxLoginRetries = nMaxLoginRetries;

	return CKR_OK;
}

CK_RV
pkcs11h_setProtectedAuthentication (
	IN const PKCS11H_BOOL fProtectedAuthentication
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);

	s_pkcs11h_data->fProtectedAuthentication = fProtectedAuthentication;

	return CKR_OK;
}

CK_RV
pkcs11h_addProvider (
	IN const char * const szReferenceName,
	IN const char * const szProvider,
	IN const PKCS11H_BOOL fProtectedAuthentication,
	IN const unsigned maskSignMode,
	IN const int nSlotEventMethod,
	IN const int nSlotEventPollInterval,
	IN const PKCS11H_BOOL fCertIsPrivate
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
#if defined(WIN32)
	int mypid = 0;
#else
	pid_t mypid = getpid ();
#endif
	pkcs11h_provider_t provider = NULL;
	CK_C_GetFunctionList gfl = NULL;
	CK_INFO info;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (szProvider!=NULL);
	/*PKCS11H_ASSERT (szSignMode!=NULL); NOT NEEDED*/

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_addProvider entry pid=%d, szReferenceName=%s, szProvider='%s', fProtectedAuthentication=%d, maskSignMode=%08x, fCertIsPrivate=%d",
		mypid,
		szReferenceName,
		szProvider,
		fProtectedAuthentication ? 1 : 0,
		maskSignMode,
		fCertIsPrivate ? 1 : 0
	);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG1,
		"PKCS#11: Adding provider '%s'-'%s'",
		szReferenceName,
		szProvider
	);

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_malloc ((void *)&provider, sizeof (struct pkcs11h_provider_s))) == CKR_OK
	) {
		strncpy (
			provider->szReferenceName,
			szReferenceName,
			sizeof (provider->szReferenceName)-1
		);
		provider->szReferenceName[sizeof (provider->szReferenceName)-1] = '\x0';
		strncpy (
			provider->manufacturerID,
			(
			 	strlen (szProvider) < sizeof (provider->manufacturerID) ?
				szProvider :
				szProvider+strlen (szProvider)-sizeof (provider->manufacturerID)+1
			),
			sizeof (provider->manufacturerID)-1
		);
		provider->manufacturerID[sizeof (provider->manufacturerID)-1] = '\x0';
		provider->fProtectedAuthentication = fProtectedAuthentication;
		provider->maskSignMode = maskSignMode;
		provider->nSlotEventMethod = nSlotEventMethod;
		provider->nSlotEventPollInterval = nSlotEventPollInterval;
		provider->fCertIsPrivate = fCertIsPrivate;
	}
		
	if (rv == CKR_OK) {
#if defined(WIN32)
		provider->hLibrary = LoadLibraryA (szProvider);
#else
		provider->hLibrary = dlopen (szProvider, RTLD_NOW);
#endif
		if (provider->hLibrary == NULL) {
			rv = CKR_FUNCTION_FAILED;
		}
	}

	if (rv == CKR_OK) {
#if defined(WIN32)
		gfl = (CK_C_GetFunctionList)GetProcAddress (
			provider->hLibrary,
			"C_GetFunctionList"
		);
#else
		/*
		 * Make compiler happy!
		 */
		void *p = dlsym (
			provider->hLibrary,
			"C_GetFunctionList"
		);
		memmove (
			&gfl, 
			&p,
			sizeof (void *)
		);
#endif
		if (gfl == NULL) {
			rv = CKR_FUNCTION_FAILED;
		}
	}

	if (rv == CKR_OK) {
		rv = gfl (&provider->f);
	}

	if (rv == CKR_OK) {
		if ((rv = provider->f->C_Initialize (NULL)) != CKR_OK) {
			if (rv == CKR_CRYPTOKI_ALREADY_INITIALIZED) {
				rv = CKR_OK;
			}
		}
		else {
			provider->fShouldFinalize = TRUE;
		}
	}

	if (
		rv == CKR_OK &&
		(rv = provider->f->C_GetInfo (&info)) == CKR_OK
	) {
		_pkcs11h_fixupFixedString (
			provider->manufacturerID,
			(char *)info.manufacturerID,
			sizeof (info.manufacturerID)
		);
	}

	if (rv == CKR_OK) {
		provider->fEnabled = TRUE;
	}

	if (provider != NULL) {
		if (s_pkcs11h_data->providers == NULL) {
			s_pkcs11h_data->providers = provider;
		}
		else {
			pkcs11h_provider_t last = NULL;
	
			for (
				last = s_pkcs11h_data->providers;
				last->next != NULL;
				last = last->next
			);
			last->next = provider;
		}
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
		fMutexLocked = FALSE;
	}
#endif

#if defined(ENABLE_PKCS11H_SLOTEVENT)
	_pkcs11h_slotevent_notify ();
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG1,
		"PKCS#11: Provider '%s' added rv=%ld-'%s'",
		szReferenceName,
		rv,
		pkcs11h_getMessage (rv)
	);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_addProvider return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_removeProvider (
	IN const char * const szReferenceName
) {
#if defined(ENABLE_PKCS11H_THREADING)
	pkcs11h_session_t current_session = NULL;
#endif
	pkcs11h_provider_t provider = NULL;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (szReferenceName!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_removeProvider entry szReferenceName='%s'",
		szReferenceName
	);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG1,
		"PKCS#11: Removing provider '%s'",
		szReferenceName
	);

#if defined(ENABLE_PKCS11H_THREADING)
	_pkcs11h_mutexLock (&s_pkcs11h_data->mutexCache);
	_pkcs11h_mutexLock (&s_pkcs11h_data->mutexSession);
	_pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal);

	for (
		current_session = s_pkcs11h_data->sessions;
		current_session != NULL;
		current_session = current_session->next
	) {
		_pkcs11h_mutexLock (&current_session->mutexSession);
	}
#endif

	provider = s_pkcs11h_data->providers;
	while (
		rv == CKR_OK &&
		provider != NULL &&
		strcmp (szReferenceName, provider->szReferenceName)
	) {
		provider = provider->next;
	}

	if (rv == CKR_OK && provider == NULL) {
		rv = CKR_OBJECT_HANDLE_INVALID;
	}

	if (rv == CKR_OK) {
		provider->fEnabled = FALSE;
		provider->szReferenceName[0] = '\0';

		if (provider->fShouldFinalize) {
			provider->f->C_Finalize (NULL);
			provider->fShouldFinalize = FALSE;
		}

#if defined(ENABLE_PKCS11H_SLOTEVENT)
		_pkcs11h_slotevent_notify ();
		
		/*
		 * Wait until manager join this thread
		 * this happens saldom so I can poll
		 */
		while (provider->threadSlotEvent != PKCS11H_THREAD_NULL) {
			_pkcs11h_sleep (500);
		}
#endif

		if (provider->f != NULL) {
			provider->f = NULL;
		}

		if (provider->hLibrary != NULL) {
#if defined(WIN32)
			FreeLibrary (provider->hLibrary);
#else
			dlclose (provider->hLibrary);
#endif
			provider->hLibrary = NULL;
		}
	}

#if defined(ENABLE_PKCS11H_THREADING)
	for (
		current_session = s_pkcs11h_data->sessions;
		current_session != NULL;
		current_session = current_session->next
	) {
		_pkcs11h_mutexRelease (&current_session->mutexSession);
	}

	_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexCache);
	_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexSession);
	_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
#endif
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_removeProvider return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_forkFixup () {
#if defined(WIN32)
	return CKR_OK;
#else
#if defined(ENABLE_PKCS11H_THREADING)
	return CKR_OK;
#else
	return _pkcs11h_forkFixup ();
#endif
#endif
}

CK_RV
pkcs11h_plugAndPlay () {
#if defined(WIN32)
	int mypid = 0;
#else
	pid_t mypid = getpid ();
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_forkFixup entry pid=%d",
		mypid
	);

	if (s_pkcs11h_data != NULL && s_pkcs11h_data->fInitialized) {
		pkcs11h_provider_t current;
#if defined(ENABLE_PKCS11H_SLOTEVENT)
		PKCS11H_BOOL fSlotEventActive = FALSE;
#endif

#if defined(ENABLE_PKCS11H_THREADING)
		_pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal);
#endif
		for (
			current = s_pkcs11h_data->providers;
			current != NULL;
			current = current->next
		) {
			if (current->fEnabled) {
				current->f->C_Finalize (NULL);
			}
		}

#if defined(ENABLE_PKCS11H_SLOTEVENT)
		if (s_pkcs11h_data->fSlotEventInitialized) {
			fSlotEventActive = TRUE;
			_pkcs11h_slotevent_terminate ();
		}
#endif

		for (
			current = s_pkcs11h_data->providers;
			current != NULL;
			current = current->next
		) {
			if (current->fEnabled) {
				current->f->C_Initialize (NULL);
			}
		}

#if defined(ENABLE_PKCS11H_SLOTEVENT)
		if (fSlotEventActive) {
			_pkcs11h_slotevent_init ();
		}
#endif

#if defined(ENABLE_PKCS11H_THREADING)
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
#endif
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_forkFixup return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_freeTokenId (
	IN pkcs11h_token_id_t token_id
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeTokenId entry certificate_id=%p",
		(void *)token_id
	);

	_pkcs11h_free ((void *)&token_id);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeTokenId return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_duplicateTokenId (
	OUT pkcs11h_token_id_t * const to,
	IN const pkcs11h_token_id_t from
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (to!=NULL);
	PKCS11H_ASSERT (from!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_duplicateTokenId entry to=%p form=%p",
		(void *)to,
		(void *)from
	);

	*to = NULL;

	if (rv == CKR_OK) {
		rv = _pkcs11h_dupmem (
			(void*)to,
			NULL,
			from,
			sizeof (struct pkcs11h_token_id_s)
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_duplicateTokenId return rv=%ld-'%s', *to=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*to
	);
	
	return rv;
}

PKCS11H_BOOL
pkcs11h_sameTokenId (
	IN const pkcs11h_token_id_t a,
	IN const pkcs11h_token_id_t b
) {
	PKCS11H_ASSERT (a!=NULL);
	PKCS11H_ASSERT (b!=NULL);

	return (
		!strcmp (a->manufacturerID, b->manufacturerID) &&
		!strcmp (a->model, b->model) &&
		!strcmp (a->serialNumber, b->serialNumber)
	);
}

/*======================================================================*
 * MEMORY INTERFACE
 *======================================================================*/

static
CK_RV
_pkcs11h_malloc (
	OUT const void ** const p,
	IN const size_t s
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (p!=NULL);
	PKCS11H_ASSERT (s!=0);

	*p = NULL;

	if (s > 0) {
		if (
			(*p = (void *)malloc (s)) == NULL
		) {
			rv = CKR_HOST_MEMORY;
		}
		else {
			memset ((void *)*p, 0, s);
		}
	}

	return rv;
}

static
CK_RV
_pkcs11h_free (
	IN const void ** const p
) {
	PKCS11H_ASSERT (p!=NULL);

	free ((void *)*p);
	*p = NULL;

	return CKR_OK;
}

static
CK_RV
_pkcs11h_dupmem (
	OUT const void ** const dest,
	OUT size_t * const p_dest_size,
	IN const void * const src,
	IN const size_t mem_size
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (dest!=NULL);
	/*PKCS11H_ASSERT (dest_size!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (!(mem_size!=0&&src==NULL));

	*dest = NULL;
	if (p_dest_size != NULL) {
		*p_dest_size = 0;
	}

	if (src != NULL) {
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_malloc (dest, mem_size)) == CKR_OK
		) {
			if (p_dest_size != NULL) {
				*p_dest_size = mem_size;
			}
			memmove ((void*)*dest, src, mem_size);
		}
	}

	return rv;
}

#if defined(ENABLE_PKCS11H_THREADING)
/*======================================================================*
 * THREADING INTERFACE
 *======================================================================*/

static
void
_pkcs11h_sleep (
	IN const unsigned milli
) {
#if defined(WIN32)
	Sleep (milli);
#else
	usleep (milli*1000);
#endif
}

static
CK_RV
_pkcs11h_mutexInit (
	OUT pkcs11h_mutex_t * const mutex
) {
	CK_RV rv = CKR_OK;
#if defined(WIN32)
	if (
		rv == CKR_OK &&
		(*mutex = CreateMutex (NULL, FALSE, NULL)) == NULL
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#else
	{
		__pkcs11h_mutex_entry_t entry = NULL;
		PKCS11H_BOOL fMutexLocked = FALSE;

		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&__s_pkcs11h_mutex_list.mutex)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
		
		if (rv == CKR_OK) {
			rv = _pkcs11h_malloc (
				(void *)&entry,
				sizeof (struct __pkcs11h_mutex_entry_s)
			);
		}

		if (
			rv == CKR_OK &&
			pthread_mutex_init (mutex, NULL)
		) {
			rv = CKR_FUNCTION_FAILED;
		}

		if (rv == CKR_OK) {
			entry->p_mutex = mutex;
			entry->next = __s_pkcs11h_mutex_list.head;
			__s_pkcs11h_mutex_list.head = entry;
			entry = NULL;
		}

		if (entry != NULL) {
			_pkcs11h_free ((void *)&entry);
		}

		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&__s_pkcs11h_mutex_list.mutex);
			fMutexLocked = FALSE;
		}
	}
#endif
	return rv;
}

static
CK_RV
_pkcs11h_mutexLock (
	IN OUT pkcs11h_mutex_t *const mutex
) {
	CK_RV rv = CKR_OK;
#if defined(WIN32)
	if (
		rv == CKR_OK &&
		WaitForSingleObject (*mutex, INFINITE) == WAIT_FAILED
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#else
	if (
		rv == CKR_OK &&
		pthread_mutex_lock (mutex)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#endif
	return rv;
}

static
CK_RV
_pkcs11h_mutexRelease (
	IN OUT pkcs11h_mutex_t *const mutex
) {
	CK_RV rv = CKR_OK;
#if defined(WIN32)
	if (
		rv == CKR_OK &&
		!ReleaseMutex (*mutex)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#else
	if (
		rv == CKR_OK &&
		pthread_mutex_unlock (mutex)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#endif
	return rv;
}

static
CK_RV
_pkcs11h_mutexFree (
	IN OUT pkcs11h_mutex_t *const mutex
) {
#if defined(WIN32)
	if (*mutex != NULL) {
		CloseHandle (*mutex);
		*mutex = NULL;
	}
#else
	{
		__pkcs11h_mutex_entry_t last = NULL;
		__pkcs11h_mutex_entry_t entry = NULL;
		PKCS11H_BOOL fMutexLocked = FALSE;

		if (_pkcs11h_mutexLock (&__s_pkcs11h_mutex_list.mutex) == CKR_OK) {
			fMutexLocked = TRUE;
		}

		entry =  __s_pkcs11h_mutex_list.head;
		while (
			entry != NULL &&
			entry->p_mutex != mutex
		) {
			last = entry;
			entry = entry->next;
		}

		if (entry != NULL) {
			if (last == NULL) {
				__s_pkcs11h_mutex_list.head = entry->next;
			}
			else {
				last->next = entry->next;
			}
			_pkcs11h_free ((void *)&entry);
		}

		pthread_mutex_destroy (mutex);

		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&__s_pkcs11h_mutex_list.mutex);
			fMutexLocked = FALSE;
		}
	}
#endif
	return CKR_OK;
}

#if !defined(WIN32)
/*
 * This function is required in order
 * to lock all mutexes before fork is called,
 * and to avoid dedlocks.
 * The loop is required because there is no
 * way to lock all mutex in one system call...
 */
static
void
__pkcs1h_mutexLockAll () {
	__pkcs11h_mutex_entry_t entry = NULL;
	PKCS11H_BOOL fMutexLocked = FALSE;
	PKCS11H_BOOL fAllLocked = FALSE;

	if (_pkcs11h_mutexLock (&__s_pkcs11h_mutex_list.mutex) == CKR_OK) {
		fMutexLocked = TRUE;
	}

	for (
		entry = __s_pkcs11h_mutex_list.head;
		entry != NULL;
		entry = entry->next
	) {
		entry->fLocked = FALSE;
	}

	while (!fAllLocked) {
		PKCS11H_BOOL fOK = TRUE;
		
		for (
			entry = __s_pkcs11h_mutex_list.head;
			entry != NULL && fOK;
			entry = entry->next
		) {
			if (!pthread_mutex_trylock (entry->p_mutex)) {
				entry->fLocked = TRUE;
			}
			else {
				fOK = FALSE;
			}
		}

		if (!fOK) {
			for (
				entry = __s_pkcs11h_mutex_list.head;
				entry != NULL;
				entry = entry->next
			) {
				if (entry->fLocked == TRUE) {
					pthread_mutex_unlock (entry->p_mutex);
					entry->fLocked = FALSE;
				}
			}

			_pkcs11h_mutexRelease (&__s_pkcs11h_mutex_list.mutex);
			_pkcs11h_sleep (1000);
			_pkcs11h_mutexLock (&__s_pkcs11h_mutex_list.mutex);
		}
		else {
			fAllLocked  = TRUE;
		}
	}

	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&__s_pkcs11h_mutex_list.mutex);
		fMutexLocked = FALSE;
	}
}

static
void
__pkcs1h_mutexReleaseAll () {
	__pkcs11h_mutex_entry_t entry = NULL;
	PKCS11H_BOOL fMutexLocked = FALSE;

	if (_pkcs11h_mutexLock (&__s_pkcs11h_mutex_list.mutex) == CKR_OK) {
		fMutexLocked = TRUE;
	}

	for (
		entry = __s_pkcs11h_mutex_list.head;
		entry != NULL;
		entry = entry->next
	) {
		pthread_mutex_unlock (entry->p_mutex);
		entry->fLocked = FALSE;
	}

	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&__s_pkcs11h_mutex_list.mutex);
		fMutexLocked = FALSE;
	}
}
#endif

CK_RV
_pkcs11h_condSignal (
	IN OUT pkcs11h_cond_t *const cond
) {
	CK_RV rv = CKR_OK;
#if defined(WIN32)
	if (
		rv == CKR_OK &&
		!SetEvent (*cond)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#else
	if (
		rv == CKR_OK &&
		(
			pthread_mutex_lock (&cond->mut) ||
			pthread_cond_signal (&cond->cond) ||
			pthread_mutex_unlock (&cond->mut)
		)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#endif

	return rv;
}

static
CK_RV
_pkcs11h_condInit (
	OUT pkcs11h_cond_t * const cond
) {
	CK_RV rv = CKR_OK;
#if defined(WIN32)
	if (
		rv == CKR_OK &&
		(*cond = CreateEvent (NULL, FALSE, FALSE, NULL)) == NULL
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#else
	if (
		rv == CKR_OK &&
		(
			pthread_mutex_init (&cond->mut, NULL) ||
			pthread_cond_init (&cond->cond, NULL) ||
			pthread_mutex_lock (&cond->mut)
		)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#endif
	return rv;
}

static
CK_RV
_pkcs11h_condWait (
	IN OUT pkcs11h_cond_t *const cond,
	IN const unsigned milli
) {
	CK_RV rv = CKR_OK;

#if defined(WIN32)
	DWORD dwMilli;

	if (milli == PKCS11H_COND_INFINITE) {
		dwMilli = INFINITE;
	}
	else {
		dwMilli = milli;
	}

	if (
		rv == CKR_OK &&
		WaitForSingleObject (*cond, dwMilli) == WAIT_FAILED
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#else
	if (milli == PKCS11H_COND_INFINITE) {
		if (
			rv == CKR_OK &&
			pthread_cond_wait (&cond->cond, &cond->mut)
		) {
			rv = CKR_FUNCTION_FAILED;
		}
	}
	else {
		struct timeval now;
		struct timespec timeout;

		if (
			rv == CKR_OK &&
			gettimeofday (&now, NULL)
		) {
			rv = CKR_FUNCTION_FAILED;
		}
		
		if (rv == CKR_OK) {
			timeout.tv_sec = now.tv_sec + milli/1000;
			timeout.tv_nsec = now.tv_usec*1000 + milli%1000;
		}
		
		if (
			rv == CKR_OK &&
			pthread_cond_timedwait (&cond->cond, &cond->mut, &timeout)
		) {
			rv = CKR_FUNCTION_FAILED;
		}
	}
#endif
	return rv;
}

static
CK_RV
_pkcs11h_condFree (
	IN OUT pkcs11h_cond_t *const cond
) {
#if defined(WIN32)
	CloseHandle (*cond);
	*cond = NULL;
#else
	pthread_mutex_unlock (&cond->mut);
#endif
	return CKR_OK;
}

#if defined(WIN32)
static
unsigned
__stdcall
__pkcs11h_thread_start (void *p) {
	__pkcs11h_thread_data_t *_data = (__pkcs11h_thread_data_t *)p;
	unsigned ret;

	ret = (unsigned)_data->start (_data->data);

	_pkcs11h_free ((void *)&_data);

	return ret;
}
#else
static
void *
__pkcs11h_thread_start (void *p) {
	__pkcs11h_thread_data_t *_data = (__pkcs11h_thread_data_t *)p;
	void *ret;
	int i;

	/*
	 * Ignore any signal in
	 * this thread
	 */
	for (i=1;i<16;i++) {
		signal (i, SIG_IGN);
	}

	ret = _data->start (_data->data);

	_pkcs11h_free ((void *)&_data);

	return ret;
}
#endif

static
CK_RV
_pkcs11h_threadStart (
	OUT pkcs11h_thread_t * const thread,
	IN pkcs11h_thread_start_t const start,
	IN void * data
) {
	__pkcs11h_thread_data_t *_data = NULL;
	CK_RV rv = CKR_OK;

	if (rv == CKR_OK) {
		rv = _pkcs11h_malloc (
			(void *)&_data,
			sizeof (__pkcs11h_thread_data_t)
		);
	}

	if (rv == CKR_OK) {
		_data->start = start;
		_data->data = data;
	}

#if defined(WIN32)
	{
		unsigned tmp;

		if (
			rv == CKR_OK &&
			(*thread = (HANDLE)_beginthreadex (
				NULL,
				0,
				__pkcs11h_thread_start,
				_data,
				0,
				&tmp
			)) == NULL
		) {
			rv = CKR_FUNCTION_FAILED;
		}
	}
#else
	if (
		rv == CKR_OK &&
		pthread_create (thread, NULL, __pkcs11h_thread_start, _data)
	) {
		rv = CKR_FUNCTION_FAILED;
	}
#endif
	return rv;
}

static
CK_RV
_pkcs11h_threadJoin (
	IN pkcs11h_thread_t * const thread
) {
#if defined(WIN32)
	WaitForSingleObject (*thread, INFINITE);
	CloseHandle (*thread);
	*thread = NULL;
#else
	pthread_join (*thread, NULL);
	*thread = 0l;
#endif
	return CKR_OK;
}

#endif		/* ENABLE_PKCS11H_THREADING */

/*======================================================================*
 * COMMON INTERNAL INTERFACE
 *======================================================================*/

static
void
_pkcs11h_fixupFixedString (
	OUT char * const szTarget,			/* MUST BE >= nLength+1 */
	IN const char * const szSource,
	IN const size_t nLength				/* FIXED STRING LENGTH */
) {
	char *p;

	PKCS11H_ASSERT (szSource!=NULL);
	PKCS11H_ASSERT (szTarget!=NULL);
	
	p = szTarget+nLength;
	memmove (szTarget, szSource, nLength);
	*p = '\0';
	p--;
	while (p >= szTarget && *p == ' ') {
		*p = '\0';
		p--;
	}
}

static
void
_pkcs11h_log (
	IN const unsigned flags,
	IN const char * const szFormat,
	IN ...
) {
	va_list args;

	PKCS11H_ASSERT (szFormat!=NULL);

	va_start (args, szFormat);

	if (
		s_pkcs11h_data != NULL &&
		s_pkcs11h_data->fInitialized
	) { 
		if (PKCS11H_MSG_LEVEL_TEST (flags)) {
			if (s_pkcs11h_data->hooks.log == NULL) {
				_pkcs11h_hooks_default_log (
					NULL,
					flags,
					szFormat,
					args
				);
			}
			else {
				s_pkcs11h_data->hooks.log (
					s_pkcs11h_data->hooks.log_data,
					flags,
					szFormat,
					args
				);
			}
		}
	}

	va_end (args);
}

static
CK_RV
_pkcs11h_getSlotList (
	IN const pkcs11h_provider_t provider,
	IN const CK_BBOOL tokenPresent,
	OUT CK_SLOT_ID_PTR * const pSlotList,
	OUT CK_ULONG_PTR pulCount
) {
	CK_SLOT_ID_PTR _slots = NULL;
	CK_ULONG _slotnum = 0;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (provider!=NULL);
	PKCS11H_ASSERT (pSlotList!=NULL);
	PKCS11H_ASSERT (pulCount!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getSlotList entry provider=%p, tokenPresent=%d, pSlotList=%p, pulCount=%p",
		(void *)provider,
		tokenPresent,
		(void *)pSlotList,
		(void *)pulCount
	);

	*pSlotList = NULL;
	*pulCount = 0;

	if (rv == CKR_OK) {
		rv = provider->f->C_GetSlotList (
			tokenPresent,
			NULL_PTR,
			&_slotnum
		);
	}

	if (rv == CKR_OK && _slotnum > 0) {
		rv = _pkcs11h_malloc ((void *)&_slots, _slotnum * sizeof (CK_SLOT_ID));
	}

	if (rv == CKR_OK && _slotnum > 0) {
		rv = provider->f->C_GetSlotList (
			tokenPresent,
			_slots,
			&_slotnum
		);
	}

	if (rv == CKR_OK) {
		*pSlotList = _slots;
		_slots = NULL;
		*pulCount = _slotnum;
	}

	if (_slots != NULL) {
		_pkcs11h_free ((void *)&_slots);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getSlotList return rv=%ld-'%s' *pulCount=%ld",
		rv,
		pkcs11h_getMessage (rv),
		*pulCount
	);

	return rv;
}

static
CK_RV
_pkcs11h_getObjectAttributes (
	IN const pkcs11h_session_t session,
	IN const CK_OBJECT_HANDLE object,
	IN OUT const CK_ATTRIBUTE_PTR attrs,
	IN const unsigned count
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (attrs!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getObjectAttributes entry session=%p, object=%ld, attrs=%p, count=%d",
		(void *)session,
		object,
		(void *)attrs,
		count
	);

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		rv == CKR_OK &&
		(rv = session->provider->f->C_GetAttributeValue (
			session->hSession,
			object,
			attrs,
			count
		)) == CKR_OK
	) {
		unsigned i;
		for (i=0;rv == CKR_OK && i<count;i++) {
			if (attrs[i].ulValueLen == (CK_ULONG)-1) {
				rv = CKR_ATTRIBUTE_VALUE_INVALID;
			}
			else {
				rv = _pkcs11h_malloc (
					(void *)&attrs[i].pValue,
					attrs[i].ulValueLen
				);
			}
		}
	}

	if (rv == CKR_OK) {
		rv = session->provider->f->C_GetAttributeValue (
			session->hSession,
			object,
			attrs,
			count
		);
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&session->mutexSession);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getObjectAttributes return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_freeObjectAttributes (
	IN OUT const CK_ATTRIBUTE_PTR attrs,
	IN const unsigned count
) {
	unsigned i;

	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (attrs!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_freeObjectAttributes entry attrs=%p, count=%d",
		(void *)attrs,
		count
	);

	for (i=0;i<count;i++) {
		if (attrs[i].pValue != NULL) {
			_pkcs11h_free ((void *)&attrs[i].pValue);
			attrs[i].pValue = NULL;
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_freeObjectAttributes return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_findObjects (
	IN const pkcs11h_session_t session,
	IN const CK_ATTRIBUTE * const filter,
	IN const CK_ULONG filter_attrs,
	OUT CK_OBJECT_HANDLE **const p_objects,
	OUT CK_ULONG *p_objects_found
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	PKCS11H_BOOL fShouldFindObjectFinal = FALSE;

	CK_OBJECT_HANDLE *objects = NULL;
	CK_ULONG objects_size = 0;
	CK_OBJECT_HANDLE objects_buffer[100];
	CK_ULONG objects_found;
	CK_OBJECT_HANDLE oLast = PKCS11H_INVALID_OBJECT_HANDLE;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (session!=NULL);
	PKCS11H_ASSERT (!(filter==NULL && filter_attrs!=0) || filter!=NULL);
	PKCS11H_ASSERT (p_objects!=NULL);
	PKCS11H_ASSERT (p_objects_found!=NULL);
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_findObjects entry session=%p, filter=%p, filter_attrs=%ld, p_objects=%p, p_objects_found=%p",
		(void *)session,
		(void *)filter,
		filter_attrs,
		(void *)p_objects,
		(void *)p_objects_found
	);

	*p_objects = NULL;
	*p_objects_found = 0;

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		rv == CKR_OK &&
		(rv = session->provider->f->C_FindObjectsInit (
			session->hSession,
			(CK_ATTRIBUTE *)filter,
			filter_attrs
		)) == CKR_OK
	) {
		fShouldFindObjectFinal = TRUE;
	}

	while (
		rv == CKR_OK &&
		(rv = session->provider->f->C_FindObjects (
			session->hSession,
			objects_buffer,
			sizeof (objects_buffer) / sizeof (CK_OBJECT_HANDLE),
			&objects_found
		)) == CKR_OK &&
		objects_found > 0
	) { 
		CK_OBJECT_HANDLE *temp = NULL;
		
		/*
		 * Begin workaround
		 *
		 * Workaround iKey bug
		 * It returns the same objects over and over
		 */
		if (oLast == objects_buffer[0]) {
			PKCS11H_LOG (
				PKCS11H_LOG_WARN,
				"PKCS#11: Bad PKCS#11 C_FindObjects implementation detected, workaround applied"
			);
			break;
		}
		oLast = objects_buffer[0];
		/* End workaround */
		
		if (
			(rv = _pkcs11h_malloc (
				(void *)&temp,
				(objects_size+objects_found) * sizeof (CK_OBJECT_HANDLE)
			)) == CKR_OK
		) {
			if (objects != NULL) {
				memmove (
					temp,
					objects,
					objects_size * sizeof (CK_OBJECT_HANDLE)
				);
			}
			memmove (
				temp + objects_size,
				objects_buffer,
				objects_found * sizeof (CK_OBJECT_HANDLE)
			);
		}

		if (rv == CKR_OK) {
			_pkcs11h_free ((void *)&objects);
			objects = temp;
			objects_size += objects_found;
			temp = NULL;
		}

		if (temp != NULL) {
			_pkcs11h_free ((void *)&temp);
			temp = NULL;
		}
	}

	if (fShouldFindObjectFinal) {
		session->provider->f->C_FindObjectsFinal (
			session->hSession
		);
		fShouldFindObjectFinal = FALSE;
	}
	
#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&session->mutexSession);
		fMutexLocked = FALSE;
	}
#endif

	if (rv == CKR_OK) {
		*p_objects = objects;
		*p_objects_found = objects_size;
		objects = NULL;
		objects_size = 0;
	}

	if (objects != NULL) {
		_pkcs11h_free ((void *)&objects);
		objects = NULL;
		objects_size = 0;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_findObjects return rv=%ld-'%s', *p_objects_found=%ld",
		rv,
		pkcs11h_getMessage (rv),
		*p_objects_found
	);

	return rv;
}

static
CK_RV
_pkcs11h_getTokenId (
	IN const CK_TOKEN_INFO_PTR info,
	OUT pkcs11h_token_id_t * const p_token_id
) {
	pkcs11h_token_id_t token_id;
	CK_RV rv = CKR_OK;
	
	PKCS11H_ASSERT (info!=NULL);
	PKCS11H_ASSERT (p_token_id!=NULL);
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getTokenId entry p_token_id=%p",
		(void *)p_token_id
	);

	*p_token_id = NULL;

	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_newTokenId (&token_id)) == CKR_OK
	) {
		_pkcs11h_fixupFixedString (
			token_id->label,
			(char *)info->label,
			sizeof (info->label)
		);
		_pkcs11h_fixupFixedString (
			token_id->manufacturerID,
			(char *)info->manufacturerID,
			sizeof (info->manufacturerID)
		);
		_pkcs11h_fixupFixedString (
			token_id->model,
			(char *)info->model,
			sizeof (info->model)
		);
		_pkcs11h_fixupFixedString (
			token_id->serialNumber,
			(char *)info->serialNumber,
			sizeof (info->serialNumber)
		);
	}

	if (rv == CKR_OK) {
		*p_token_id = token_id;
		token_id = NULL;
	}

	if (token_id != NULL) {
		_pkcs11h_free ((void *)&token_id);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getTokenId return rv=%ld-'%s', *p_token_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_token_id
	);

	return rv;
}

static
CK_RV
_pkcs11h_newTokenId (
	OUT pkcs11h_token_id_t * const p_token_id
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (p_token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_newTokenId entry p_token_id=%p",
		(void *)p_token_id
	);

	*p_token_id = NULL;

	if (rv == CKR_OK) {
		rv = _pkcs11h_malloc ((void *)p_token_id, sizeof (struct pkcs11h_token_id_s));
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_newTokenId return rv=%ld-'%s', *p_token_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_token_id
	);

	return rv;
}

static
CK_RV
_pkcs11h_getSessionByTokenId (
	IN const pkcs11h_token_id_t token_id,
	OUT pkcs11h_session_t * const p_session
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	pkcs11h_session_t session = NULL;
	PKCS11H_BOOL fNewSession = FALSE;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (token_id!=NULL);
	PKCS11H_ASSERT (p_session!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getSessionByTokenId entry token_id=%p, p_session=%p",
		(void *)token_id,
		(void *)p_session
	);

	*p_session = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexSession)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (rv == CKR_OK) {
		pkcs11h_session_t current_session;

		for (
			current_session = s_pkcs11h_data->sessions;
			current_session != NULL && session == NULL;
			current_session = current_session->next
		) {
			if (
				pkcs11h_sameTokenId (
					current_session->token_id,
					token_id
				)
			) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Using cached session"
				);
				session = current_session;
				session->nReferenceCount++;
			}
		}
	}

	if (
		rv == CKR_OK &&
		session == NULL
	) {
		fNewSession = TRUE;
	}

	if (fNewSession) {
		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Creating a new session"
		);

		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_malloc ((void *)&session, sizeof (struct pkcs11h_session_s))) == CKR_OK
		) {
			session->nReferenceCount = 1;
			session->hSession = PKCS11H_INVALID_SESSION_HANDLE;
			
			session->nPINCachePeriod = s_pkcs11h_data->nPINCachePeriod;

		}

		if (rv == CKR_OK) {
			rv = pkcs11h_duplicateTokenId (
				&session->token_id,
				token_id
			);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (rv == CKR_OK) {
			rv = _pkcs11h_mutexInit (&session->mutexSession);
		}
#endif

		if (rv == CKR_OK) {
			session->fValid = TRUE;
			session->next = s_pkcs11h_data->sessions;
			s_pkcs11h_data->sessions = session;
		}
		else {
#if defined(ENABLE_PKCS11H_THREADING)
			_pkcs11h_mutexFree (&session->mutexSession);
#endif
			_pkcs11h_free ((void *)&session);
		}
	}

	if (rv == CKR_OK) {
		*p_session = session;
		session = NULL;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexSession);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getSessionByTokenId return rv=%ld-'%s', *p_session=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_session
	);

	return rv;
}

static
CK_RV
_pkcs11h_releaseSession (
	IN const pkcs11h_session_t session
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (session!=NULL);
	PKCS11H_ASSERT (session->nReferenceCount>=0);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_releaseSession session=%p",
		(void *)session
	);

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	/*
	 * Never logout for now
	 */
	if (rv == CKR_OK) {
		if (session->nReferenceCount > 0) {
			session->nReferenceCount--;
		}
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&session->mutexSession);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_releaseSession return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_resetSession (
	IN const pkcs11h_session_t session,
	IN const unsigned maskPrompt,
	OUT CK_SLOT_ID * const p_slot
) {
	/*
	 * This function MUST NOT touch session
	 */
	PKCS11H_BOOL fFound = FALSE;

	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (session!=NULL);
	PKCS11H_ASSERT (p_slot!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_resetSession entry session=%p, maskPrompt=%08x, p_slot=%p",
		(void *)session,
		maskPrompt,
		(void *)p_slot
	);

	*p_slot = PKCS11H_INVALID_SLOT_ID;

	while (
		rv == CKR_OK &&
		!fFound
	) {
		pkcs11h_provider_t current_provider = NULL;
#if defined(ENABLE_PKCS11H_THREADING)
		PKCS11H_BOOL fMutexLocked = FALSE;
#endif

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		for (
			current_provider = s_pkcs11h_data->providers;
			(
				rv == CKR_OK &&
				current_provider != NULL &&
				!fFound
			);
			current_provider = current_provider->next
		) {
			CK_SLOT_ID_PTR slots = NULL;
			CK_ULONG slotnum;
			CK_SLOT_ID slot_index;

			/*
			 * Skip disabled providers
			 * Skip all other providers,
			 * if one was set in the past
			 */
			if (session->provider != NULL) {
				if (!session->provider->fEnabled) {
					continue;
				}
				if (session->provider != current_provider) {
					continue;
				}
			}
		
			if (rv == CKR_OK) {
				rv = _pkcs11h_getSlotList (
					current_provider,
					CK_TRUE,
					&slots,
					&slotnum
				);
			}

			for (
				slot_index=0;
				(
					slot_index < slotnum &&
					rv == CKR_OK && 
					!fFound
				);
				slot_index++
			) {
				pkcs11h_token_id_t token_id = NULL;
				CK_TOKEN_INFO info;

				if (rv == CKR_OK) {
					rv = current_provider->f->C_GetTokenInfo (
						slots[slot_index],
						&info
					);
				}

				if (
					rv == CKR_OK &&
					(rv = _pkcs11h_getTokenId (
						&info,
						&token_id
					)) == CKR_OK &&
					pkcs11h_sameTokenId (
						session->token_id,
						token_id
					)
				) {
					fFound = TRUE;
					*p_slot = slots[slot_index];
					if (session->provider == NULL) {
						session->provider = current_provider;
						_pkcs11h_fixupFixedString (
							token_id->label,
							(char *)info.label,
							sizeof (info.label)
						);
						session->fProtectedAuthenticationSupported = (info.flags & CKF_PROTECTED_AUTHENTICATION_PATH) != 0;
					}
				}

				if (rv != CKR_OK) {
					PKCS11H_DEBUG (
						PKCS11H_LOG_DEBUG1,
						"PKCS#11: Cannot get token information for provider '%s' slot %ld rv=%ld-'%s'",
						current_provider->manufacturerID,
						slots[slot_index],
						rv,
						pkcs11h_getMessage (rv)
					);

					/*
					 * Ignore error
					 */
					rv = CKR_OK;
				}

				if (token_id != NULL) {
					pkcs11h_freeTokenId (token_id);
				}
			}

			if (rv != CKR_OK) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Cannot get slot list for provider '%s' rv=%ld-'%s'",
					current_provider->manufacturerID,
					rv,
					pkcs11h_getMessage (rv)
				);

				/*
				 * Ignore error
				 */
				rv = CKR_OK;
			}

			if (slots != NULL) {
				_pkcs11h_free ((void *)&slots);
				slots = NULL;
			}
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif

		if (
			rv == CKR_OK &&
			!fFound
		) {
			if ((maskPrompt & PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT) != 0) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Calling token_prompt hook for '%s'",
					session->token_id->label
				);
		
				if (
					!s_pkcs11h_data->hooks.token_prompt (
						s_pkcs11h_data->hooks.token_prompt_data,
						session->token_id
					)
				) {
					rv = CKR_CANCEL;
				}

				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: token_prompt returned %ld",
					rv
				);
			}
			else {
				rv = CKR_TOKEN_NOT_PRESENT;
			}
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_resetSession return rv=%ld-'%s', *p_slot=%ld",
		rv,
		pkcs11h_getMessage (rv),
		*p_slot
	);

	return rv;
}

static
CK_RV
_pkcs11h_getObjectById (
	IN const pkcs11h_session_t session,
	IN const CK_OBJECT_CLASS class,
	IN const CK_BYTE_PTR id,
	IN const size_t id_size,
	OUT CK_OBJECT_HANDLE * const p_handle
) {
	CK_ATTRIBUTE filter[] = {
		{CKA_CLASS, (void *)&class, sizeof (class)},
		{CKA_ID, (void *)id, id_size}
	};
	CK_OBJECT_HANDLE *objects = NULL;
	CK_ULONG objects_found = 0;
	CK_RV rv = CKR_OK;
	
	/*PKCS11H_ASSERT (session!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (id!=NULL);
	PKCS11H_ASSERT (p_handle!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getObjectById entry session=%p, class=%ld, id=%p, id_size=%u, p_handle=%p",
		(void *)session,
		class,
		id,
		id_size,
		(void *)p_handle
	);

	*p_handle = PKCS11H_INVALID_OBJECT_HANDLE;

	if (rv == CKR_OK) {
		rv = _pkcs11h_validateSession (session);
	}

	if (rv == CKR_OK) { 
		rv = _pkcs11h_findObjects (
			session,
			filter,
			sizeof (filter) / sizeof (CK_ATTRIBUTE),
			&objects,
			&objects_found
		);
	}

	if (
		rv == CKR_OK &&
		objects_found == 0
	) {
		rv = CKR_FUNCTION_REJECTED;
	}

	if (rv == CKR_OK) {
		*p_handle = objects[0];
	}

	if (objects != NULL) {
		_pkcs11h_free ((void *)&objects);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getObjectById return rv=%ld-'%s', *p_handle=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_handle
	);

	return rv;
}

static
CK_RV
_pkcs11h_validateSession (
	IN const pkcs11h_session_t session
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	CK_RV rv = CKR_OK;

	/*PKCS11H_ASSERT (session!=NULL); NOT NEEDED*/

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_validateSession entry session=%p",
		(void *)session
	);

	if (
		rv == CKR_OK &&
		session == NULL
	) {
		rv = CKR_SESSION_HANDLE_INVALID;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		rv == CKR_OK &&
		(
			session->provider == NULL ||
			!session->provider->fEnabled ||
			session->hSession == PKCS11H_INVALID_SESSION_HANDLE
		)
	) {
		rv = CKR_SESSION_HANDLE_INVALID;
	}

	if (
		rv == CKR_OK &&
		session->timePINExpire != (time_t)0 &&
		session->timePINExpire < PKCS11H_TIME (NULL)
	) {
		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Forcing logout due to pin timeout"
		);
		_pkcs11h_logout (session);
		rv = CKR_SESSION_HANDLE_INVALID;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&session->mutexSession);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_validateSession return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_login (
	IN const pkcs11h_session_t session,
	IN const PKCS11H_BOOL fPublicOnly,
	IN const PKCS11H_BOOL fReadOnly,
	IN const unsigned maskPrompt
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	CK_SLOT_ID slot = PKCS11H_INVALID_SLOT_ID;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (session!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_login entry session=%p, fPublicOnly=%d, fReadOnly=%d, maskPrompt=%08x",
		(void *)session,
		fPublicOnly ? 1 : 0,
		fReadOnly ? 1 : 0,
		maskPrompt
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_logout (session);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_resetSession (session, maskPrompt, &slot);
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (rv == CKR_OK) {
		rv = session->provider->f->C_OpenSession (
			slot,
			(
				CKF_SERIAL_SESSION |
				(fReadOnly ? 0 : CKF_RW_SESSION)
			),
			NULL_PTR,
			NULL_PTR,
			&session->hSession
		);
	}

	if (
		rv == CKR_OK &&
	   	(
			!fPublicOnly ||
			session->provider->fCertIsPrivate
		)
	) {
		PKCS11H_BOOL fSuccessLogin = FALSE;
		int nRetryCount = 0;

		if ((maskPrompt & PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT) == 0) {
			rv = CKR_USER_NOT_LOGGED_IN;

			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Calling pin_prompt hook denied because of prompt mask"
			);
		}

		while (
			rv == CKR_OK &&
			!fSuccessLogin &&
			nRetryCount++ < s_pkcs11h_data->nMaxLoginRetries 
		) {
			CK_UTF8CHAR_PTR utfPIN = NULL;
			CK_ULONG lPINLength = 0;
			char szPIN[1024];

			if (
				rv == CKR_OK &&
				!(
					s_pkcs11h_data->fProtectedAuthentication  &&
					session->provider->fProtectedAuthentication &&
					session->fProtectedAuthenticationSupported
				)
			) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Calling pin_prompt hook for '%s'",
					session->token_id->label
				);

				if (
					!s_pkcs11h_data->hooks.pin_prompt (
						s_pkcs11h_data->hooks.pin_prompt_data,
						session->token_id,
						szPIN,
						sizeof (szPIN)
					)
				) {
					rv = CKR_CANCEL;
				}
				else {
					utfPIN = (CK_UTF8CHAR_PTR)szPIN;
					lPINLength = strlen (szPIN);
				}

				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: pin_prompt hook return rv=%ld",
					rv
				);

			}

			if (session->nPINCachePeriod == PKCS11H_PIN_CACHE_INFINITE) {
				session->timePINExpire = 0;
			}
			else {
				session->timePINExpire = (
					PKCS11H_TIME (NULL) +
					(time_t)session->nPINCachePeriod
				);
			}

			if (
				rv == CKR_OK &&
				(rv = session->provider->f->C_Login (
					session->hSession,
					CKU_USER,
					utfPIN,
					lPINLength
				)) != CKR_OK
			) {
				if (rv == CKR_USER_ALREADY_LOGGED_IN) {
					rv = CKR_OK;
				}
			}

			/*
			 * Clean PIN buffer
			 */
			memset (szPIN, 0, sizeof (szPIN));

			if (rv == CKR_OK) {
				fSuccessLogin = TRUE;
			}
			else if (
				rv == CKR_PIN_INCORRECT ||
				rv == CKR_PIN_INVALID
			) {
				/*
				 * Ignore these errors
				 * so retry can be performed
				 */
				rv = CKR_OK;
			}
		}
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&session->mutexSession);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_login return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_logout (
	IN const pkcs11h_session_t session
) {
	/*PKCS11H_ASSERT (session!=NULL); NOT NEEDED*/

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_logout entry session=%p",
		(void *)session
	);

	if (
		session != NULL &&
		session->hSession != PKCS11H_INVALID_SESSION_HANDLE
	) {
#if defined(ENABLE_PKCS11H_THREADING)
		PKCS11H_BOOL fMutexLocked = FALSE;
#endif
		CK_RV rv = CKR_OK;

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (rv == CKR_OK) {
			if (session->provider != NULL) {
				session->provider->f->C_Logout (session->hSession);
				session->provider->f->C_CloseSession (session->hSession);
			}
			session->hSession = PKCS11H_INVALID_SESSION_HANDLE;
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_logout return"
	);

	return CKR_OK;
}

static
void
_pkcs11h_hooks_default_log (
	IN const void * pData,
	IN const unsigned flags,
	IN const char * const szFormat,
	IN va_list args
) {
	(void)pData;
	(void)flags;
	(void)szFormat;
	(void)args;
}

static
PKCS11H_BOOL
_pkcs11h_hooks_default_token_prompt (
	IN const void * pData,
	IN const pkcs11h_token_id_t token
) {
	PKCS11H_ASSERT (token!=NULL);

	(void)pData;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_hooks_default_token_prompt pData=%p, szLabel='%s'",
		pData,
		token->label
	);

	return FALSE;
}

static
PKCS11H_BOOL
_pkcs11h_hooks_default_pin_prompt (
	IN const void * pData,
	IN const pkcs11h_token_id_t token,
	OUT char * const szPIN,
	IN const size_t nMaxPIN
) {
	PKCS11H_ASSERT (token!=NULL);

	(void)pData;
	(void)szPIN;
	(void)nMaxPIN;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_hooks_default_pin_prompt pData=%p, szLabel='%s'",
		pData,
		token->label
	);
	
	return FALSE;
}

#if !defined(WIN32)
#if defined(ENABLE_PKCS11H_THREADING)

static
void
__pkcs11h_atfork_prepare  () {
	__pkcs1h_mutexLockAll ();
}
static
void
__pkcs11h_atfork_parent () {
	__pkcs1h_mutexReleaseAll ();
}
static
void
__pkcs11h_atfork_child () {
	__pkcs1h_mutexReleaseAll ();
	_pkcs11h_forkFixup ();
}

#endif				/* ENABLE_PKCS11H_THREADING */

static
CK_RV
_pkcs11h_forkFixup () {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	pid_t mypid = getpid ();

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_forkFixup entry pid=%d",
		mypid
	);

	if (s_pkcs11h_data != NULL && s_pkcs11h_data->fInitialized) {
		pkcs11h_provider_t current;

#if defined(ENABLE_PKCS11H_THREADING)
		if (_pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal) == CKR_OK) {
			fMutexLocked = TRUE;
		}
#endif

		for (
			current = s_pkcs11h_data->providers;
			current != NULL;
			current = current->next
		) {
			if (current->fEnabled) {
				current->f->C_Initialize (NULL);
			}

#if defined(ENABLE_PKCS11H_SLOTEVENT)
			/*
			 * After fork we have no threads...
			 * So just initialized.
			 */
			if (s_pkcs11h_data->fSlotEventInitialized) {
				s_pkcs11h_data->fSlotEventInitialized = FALSE;
				_pkcs11h_slotevent_init ();
			}
#endif
		}
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_forkFixup return"
	);

	return CKR_OK;
}

#endif				/* !WIN32 */

#if defined(ENABLE_PKCS11H_TOKEN)
/*======================================================================*
 * TOKEN INTERFACE
 *======================================================================*/

CK_RV
pkcs11h_token_ensureAccess (
	IN const pkcs11h_token_id_t token_id,
	IN const unsigned maskPrompt
) {
	pkcs11h_session_t session = NULL;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_token_ensureAccess entry token_id=%p, maskPrompt=%08x",
		(void *)token_id,
		maskPrompt
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_getSessionByTokenId (
			token_id,
			&session
		);
	}

	if (rv == CKR_OK) {
		CK_SLOT_ID slot;

		rv = _pkcs11h_resetSession (
			session,
			maskPrompt,
			&slot
		);
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_token_ensureAccess return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

#endif				/* ENABLE_PKCS11H_TOKEN */

#if defined(ENABLE_PKCS11H_DATA)
/*======================================================================*
 * DATA INTERFACE
 *======================================================================*/

static
CK_RV
_pkcs11h_data_getObject (
	IN const pkcs11h_session_t session,
	IN const char * const szApplication,
	IN const char * const szLabel,
	OUT CK_OBJECT_HANDLE * const p_handle
) {
	CK_OBJECT_CLASS class = CKO_DATA;
	CK_ATTRIBUTE filter[] = {
		{CKA_CLASS, (void *)&class, sizeof (class)},
		{CKA_APPLICATION, (void *)szApplication, szApplication == NULL ? 0 : strlen (szApplication)},
		{CKA_LABEL, (void *)szLabel, szLabel == NULL ? 0 : strlen (szLabel)}
	};
	CK_OBJECT_HANDLE *objects = NULL;
	CK_ULONG objects_found = 0;
	CK_RV rv = CKR_OK;
	
	/*PKCS11H_ASSERT (session!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (szApplication!=NULL);
	PKCS11H_ASSERT (szLabel!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_data_getObject entry session=%p, szApplication='%s', szLabel='%s', p_handle=%p",
		(void *)session,
		szApplication,
		szLabel,
		(void *)p_handle
	);

	*p_handle = PKCS11H_INVALID_OBJECT_HANDLE;

	if (rv == CKR_OK) {
		rv = _pkcs11h_validateSession (session);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_findObjects (
			session,
			filter,
			sizeof (filter) / sizeof (CK_ATTRIBUTE),
			&objects,
			&objects_found
		);
	}

	if (
		rv == CKR_OK &&
		objects_found == 0
	) {
		rv = CKR_FUNCTION_REJECTED;
	}

	if (rv == CKR_OK) {
		*p_handle = objects[0];
	}

	if (objects != NULL) {
		_pkcs11h_free ((void *)&objects);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_data_getObject return rv=%ld-'%s', *p_handle=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_handle
	);

	return rv;
}

CK_RV
pkcs11h_data_get (
	IN const pkcs11h_token_id_t token_id,
	IN const PKCS11H_BOOL fPublic,
	IN const char * const szApplication,
	IN const char * const szLabel,
	OUT char * const blob,
	IN OUT size_t * const p_blob_size
) {
	CK_ATTRIBUTE attrs[] = {
		{CKA_VALUE, NULL, 0}
	};
	CK_OBJECT_HANDLE handle = PKCS11H_INVALID_OBJECT_HANDLE;
	CK_RV rv = CKR_OK;

	pkcs11h_session_t session = NULL;
	size_t blob_size_max;
	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;
	PKCS11H_BOOL fMutexLocked = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (token_id!=NULL);
	PKCS11H_ASSERT (szApplication!=NULL);
	PKCS11H_ASSERT (szLabel!=NULL);
	/*PKCS11H_ASSERT (blob!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (p_blob_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_get entry token_id=%p, szApplication='%s', szLabel='%s', blob=%p, p_blob_size=%p",
		(void *)token_id,
		szApplication,
		szLabel,
		blob,
		(void *)p_blob_size
	);

	blob_size_max = *p_blob_size;
	*p_blob_size = 0;

	if (rv == CKR_OK) {
		rv = _pkcs11h_getSessionByTokenId (
			token_id,
			&session
		);
	}

	while (rv == CKR_OK && !fOpSuccess) {

		if (rv == CKR_OK) {
			rv = _pkcs11h_validateSession (session);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (rv == CKR_OK) {
			rv = _pkcs11h_data_getObject (
				session,
				szApplication,
				szLabel,
				&handle
			);
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_getObjectAttributes (
				session,
				handle,
				attrs,
				sizeof (attrs)/sizeof (CK_ATTRIBUTE)
			);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Read data object failed rv=%ld-'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);
				fLoginRetry = TRUE;
				rv = _pkcs11h_login (
					session,
					fPublic,
					TRUE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);
			}
		}
	}

	if (rv == CKR_OK) {
		*p_blob_size = attrs[0].ulValueLen;
	}

	if (rv == CKR_OK) {
		if (blob != NULL) {
			if (*p_blob_size > blob_size_max) {
				rv = CKR_BUFFER_TOO_SMALL;
			}
			else {
				memmove (blob, attrs[0].pValue, *p_blob_size);
			}
		}
	}

	_pkcs11h_freeObjectAttributes (
		attrs,
		sizeof (attrs)/sizeof (CK_ATTRIBUTE)
	);

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_get return rv=%ld-'%s', *p_blob_size=%d",
		rv,
		pkcs11h_getMessage (rv),
		*p_blob_size
	);

	return rv;
}

CK_RV
pkcs11h_data_put (
	IN const pkcs11h_token_id_t token_id,
	IN const PKCS11H_BOOL fPublic,
	IN const char * const szApplication,
	IN const char * const szLabel,
	OUT char * const blob,
	IN const size_t blob_size
) {
	CK_OBJECT_CLASS class = CKO_DATA;
	CK_BBOOL ck_true = CK_TRUE;
	CK_BBOOL ck_false = CK_FALSE;

	CK_ATTRIBUTE attrs[] = {
		{CKA_CLASS, &class, sizeof (class)},
		{CKA_TOKEN, &ck_true, sizeof (ck_true)},
		{CKA_PRIVATE, fPublic ? &ck_false : &ck_true, sizeof (CK_BBOOL)},
		{CKA_APPLICATION, (void *)szApplication, strlen (szApplication)},
		{CKA_LABEL, (void *)szLabel, strlen (szLabel)},
		{CKA_VALUE, blob, blob_size}
	};

	CK_OBJECT_HANDLE handle = PKCS11H_INVALID_OBJECT_HANDLE;
	CK_RV rv = CKR_OK;

	pkcs11h_session_t session = NULL;
	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;
	PKCS11H_BOOL fMutexLocked = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (token_id!=NULL);
	PKCS11H_ASSERT (szApplication!=NULL);
	PKCS11H_ASSERT (szLabel!=NULL);
	PKCS11H_ASSERT (blob!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_put entry token_id=%p, szApplication='%s', szLabel='%s', blob=%p, blob_size=%d",
		(void *)token_id,
		szApplication,
		szLabel,
		blob,
		blob_size
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_getSessionByTokenId (
			token_id,
			&session
		);
	}

	while (rv == CKR_OK && !fOpSuccess) {

		if (rv == CKR_OK) {
			rv = _pkcs11h_validateSession (session);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (rv == CKR_OK) {
			rv = session->provider->f->C_CreateObject (
				session->hSession,
				attrs,
				sizeof (attrs)/sizeof (CK_ATTRIBUTE),
				&handle
			);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Write data object failed rv=%ld-'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);
				fLoginRetry = TRUE;
				rv = _pkcs11h_login (
					session,
					fPublic,
					FALSE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);
			}
		}
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_put return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_data_del (
	IN const pkcs11h_token_id_t token_id,
	IN const PKCS11H_BOOL fPublic,
	IN const char * const szApplication,
	IN const char * const szLabel
) {
	CK_OBJECT_HANDLE handle = PKCS11H_INVALID_OBJECT_HANDLE;
	CK_RV rv = CKR_OK;

	pkcs11h_session_t session = NULL;
	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;
	PKCS11H_BOOL fMutexLocked = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (token_id!=NULL);
	PKCS11H_ASSERT (szApplication!=NULL);
	PKCS11H_ASSERT (szLabel!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_del entry token_id=%p, szApplication='%s', szLabel='%s'",
		(void *)token_id,
		szApplication,
		szLabel
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_getSessionByTokenId (
			token_id,
			&session
		);
	}

	while (rv == CKR_OK && !fOpSuccess) {

		if (rv == CKR_OK) {
			rv = _pkcs11h_validateSession (session);
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_data_getObject (
				session,
				szApplication,
				szLabel,
				&handle
			);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (rv == CKR_OK) {
			rv = session->provider->f->C_DestroyObject (
				session->hSession,
				handle
			);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Remove data object failed rv=%ld-'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);
				fLoginRetry = TRUE;
				rv = _pkcs11h_login (
					session,
					fPublic,
					FALSE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);
			}
		}
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_del return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

#endif				/* ENABLE_PKCS11H_DATA */

#if defined(ENABLE_PKCS11H_CERTIFICATE)
/*======================================================================*
 * CERTIFICATE INTERFACE
 *======================================================================*/

static
void
_pkcs11h_isBetterCertificate_getExpiration (
	IN const unsigned char * const pCertificate,
	IN const size_t nCertificateSize,
	OUT char * const szNotBefore,
	IN const int nNotBeforeSize
) {
	/*
	 * This function compare the notBefore
	 * and select the most recent certificate
	 * it does not deal with timezones...
	 * When openssl will have ASN1_TIME compare function
	 * it should be used.
	 */

	X509 *x509 = NULL;

	PKCS11H_ASSERT (pCertificate!=NULL);
	PKCS11H_ASSERT (szNotBefore!=NULL);
	PKCS11H_ASSERT (nNotBeforeSize>0);

	szNotBefore[0] = '\0';

	x509 = X509_new ();

	if (x509 != NULL) {
		pkcs11_openssl_d2i_t d2i = (pkcs11_openssl_d2i_t)pCertificate;

		if (
			d2i_X509 (&x509, &d2i, nCertificateSize)
		) {
			ASN1_TIME *notBefore = X509_get_notBefore (x509);
			ASN1_TIME *notAfter = X509_get_notAfter (x509);

			if (
				notBefore != NULL &&
				X509_cmp_current_time (notBefore) <= 0 &&
				X509_cmp_current_time (notAfter) >= 0 &&
				notBefore->length < nNotBeforeSize - 1
			) {
				memmove (szNotBefore, notBefore->data, notBefore->length);
				szNotBefore[notBefore->length] = '\0';
			}
		}
	}

	if (x509 != NULL) {
		X509_free (x509);
		x509 = NULL;
	}
}

static
PKCS11H_BOOL
_pkcs11h_isBetterCertificate (
	IN const unsigned char * const pCurrent,
	IN const size_t nCurrentSize,
	IN const unsigned char * const pNew,
	IN const size_t nNewSize
) {
	/*
	 * This function compare the notBefore
	 * and select the most recent certificate
	 * it does not deal with timezones...
	 * When openssl will have ASN1_TIME compare function
	 * it should be used.
	 */

	PKCS11H_BOOL fBetter = FALSE;

	/*PKCS11H_ASSERT (pCurrent!=NULL); NOT NEEDED */
	PKCS11H_ASSERT (pNew!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_isBetterCertificate entry pCurrent=%p, nCurrentSize=%u, pNew=%p, nNewSize=%u",
		pCurrent,
		nCurrentSize,
		pNew,
		nNewSize
	);

	/*
	 * First certificae
	 * always select
	 */
	if (nCurrentSize == 0 || pCurrent == NULL) {
		fBetter = TRUE;
	}
	else {
		char szNotBeforeCurrent[1024], szNotBeforeNew[1024];

		_pkcs11h_isBetterCertificate_getExpiration (
			pCurrent,
			nCurrentSize,
			szNotBeforeCurrent,
			sizeof (szNotBeforeCurrent)
		);
		_pkcs11h_isBetterCertificate_getExpiration (
			pNew,
			nNewSize,
			szNotBeforeNew,
			sizeof (szNotBeforeNew)
		);

		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG2,
			"PKCS#11: _pkcs11h_isBetterCertificate szNotBeforeCurrent='%s', szNotBeforeNew='%s'",
			szNotBeforeCurrent,
			szNotBeforeNew
		);

		fBetter = strcmp (szNotBeforeCurrent, szNotBeforeNew) < 0;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_isBetterCertificate return fBetter=%d",
		fBetter ? 1 : 0
	);
	
	return fBetter;
}

static
CK_RV
_pkcs11h_newCertificateId (
	OUT pkcs11h_certificate_id_t * const p_certificate_id
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (p_certificate_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_newCertificateId entry p_certificate_id=%p",
		(void *)p_certificate_id
	);

	*p_certificate_id = NULL;

	if (rv == CKR_OK) {
		rv = _pkcs11h_malloc ((void *)p_certificate_id, sizeof (struct pkcs11h_certificate_id_s));
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_newCertificateId return rv=%ld-'%s', *p_certificate_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_certificate_id
	);

	return rv;
}

static
CK_RV
_pkcs11h_loadCertificate (
	IN const pkcs11h_certificate_t certificate
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	CK_OBJECT_CLASS cert_filter_class = CKO_CERTIFICATE;
	CK_ATTRIBUTE cert_filter[] = {
		{CKA_CLASS, &cert_filter_class, sizeof (cert_filter_class)},
		{CKA_ID, NULL, 0}
	};

	CK_OBJECT_HANDLE *objects = NULL;
	CK_ULONG objects_found = 0;
	CK_RV rv = CKR_OK;

	CK_ULONG i;

	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (certificate->id!=NULL);
	
	/* Must be after assert */
	cert_filter[1].pValue = certificate->id->attrCKA_ID;
	cert_filter[1].ulValueLen = certificate->id->attrCKA_ID_size;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_loadCertificate entry certificate=%p",
		(void *)certificate
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_validateSession (certificate->session);
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&certificate->mutexCertificate)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (rv == CKR_OK) {
		rv = _pkcs11h_findObjects (
			certificate->session,
			cert_filter,
			sizeof (cert_filter) / sizeof (CK_ATTRIBUTE),
			&objects,
			&objects_found
		);
	}

	for (i=0;rv == CKR_OK && i < objects_found;i++) {
		CK_ATTRIBUTE attrs[] = {
			{CKA_VALUE, NULL, 0}
		};

		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_getObjectAttributes (
				certificate->session,
				objects[i],
				attrs,
				sizeof (attrs) / sizeof (CK_ATTRIBUTE)
			)) == CKR_OK
		) {
			if (
				_pkcs11h_isBetterCertificate (
					certificate->id->certificate_blob,
					certificate->id->certificate_blob_size,
					attrs[0].pValue,
					attrs[0].ulValueLen
				)
			) {
				if (certificate->id->certificate_blob != NULL) {
					_pkcs11h_free ((void *)&certificate->id->certificate_blob);
				}

				rv = _pkcs11h_dupmem (
					(void*)&certificate->id->certificate_blob,
					&certificate->id->certificate_blob_size,
					attrs[0].pValue,
					attrs[0].ulValueLen
				);
			}
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get object attribute for provider '%s' object %ld rv=%ld-'%s'",
				certificate->session->provider->manufacturerID,
				objects[i],
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		_pkcs11h_freeObjectAttributes (
			attrs,
			sizeof (attrs) / sizeof (CK_ATTRIBUTE)
		);
	}
	
	if (
		rv == CKR_OK &&
		certificate->id->certificate_blob == NULL
	) {
		rv = CKR_ATTRIBUTE_VALUE_INVALID;
	}

	if (objects != NULL) {
		_pkcs11h_free ((void *)&objects);
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&certificate->mutexCertificate);
		fMutexLocked = FALSE;
	}
#endif

	/*
	 * No need to free allocated objects
	 * on error, since the certificate_id
	 * should be free by caller.
	 */

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_loadCertificate return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_updateCertificateIdDescription (
	IN OUT pkcs11h_certificate_id_t certificate_id
) {
	static const char * szSeparator = " on ";
	static const char * szUnknown = "UNKNOWN";
	X509 *x509 = NULL;
	pkcs11_openssl_d2i_t d2i1;

	PKCS11H_ASSERT (certificate_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_updateCertificateIdDescription entry certificate_id=%p",
		(void *)certificate_id
	);

	x509 = X509_new ();

	d2i1 = (pkcs11_openssl_d2i_t)certificate_id->certificate_blob;
	if (d2i_X509 (&x509, &d2i1, certificate_id->certificate_blob_size)) {
		X509_NAME_oneline (
			X509_get_subject_name (x509),
			certificate_id->displayName,
			sizeof (certificate_id->displayName)
		);
	}
	else {
		strncpy (
			certificate_id->displayName,
			szUnknown,
			sizeof (certificate_id->displayName)-1
		);
	}

	if (x509 != NULL) {
		X509_free (x509);
		x509 = NULL;
	}

	/*
	 * Try to avoid using snprintf,
	 * may be unavailable
	 */
	strncat (
		certificate_id->displayName,
		szSeparator,
		sizeof (certificate_id->displayName)-1-strlen (certificate_id->displayName)
	);
	strncat (
		certificate_id->displayName,
		certificate_id->token_id->label,
		sizeof (certificate_id->displayName)-1-strlen (certificate_id->displayName)
	);
	certificate_id->displayName[sizeof (certificate_id->displayName) - 1] = '\0';

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_updateCertificateIdDescription return displayName=%s",
		certificate_id->displayName
	);

	return CKR_OK;
}

static
CK_RV
_pkcs11h_ensureCertificateBlob (
	IN const pkcs11h_certificate_t certificate
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;

	CK_RV rv = CKR_OK;
	
	PKCS11H_ASSERT (certificate!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_ensureCertificateBlob entry certificate=%p",
		(void *)certificate
	);

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&certificate->mutexCertificate)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (certificate->id->certificate_blob == NULL) {
		fOpSuccess = FALSE;
		fLoginRetry = FALSE;
		while (rv == CKR_OK && !fOpSuccess) {
			if (rv == CKR_OK) {
				rv = _pkcs11h_loadCertificate (certificate);
			}

			if (rv == CKR_OK) {
				fOpSuccess = TRUE;
			}
			else {
				if (!fLoginRetry) {
					fLoginRetry = TRUE;
					rv = _pkcs11h_resetCertificateSession (
						certificate,
						TRUE,
						(
							PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
							PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
						)
					);
				}
			}
		}
	}
	
	if (
		rv == CKR_OK &&
		certificate->id->certificate_blob == NULL
	) {
		rv = CKR_FUNCTION_REJECTED;
	}

	if (rv == CKR_OK) {
		_pkcs11h_updateCertificateIdDescription (certificate->id);
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&certificate->mutexCertificate);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_ensureCertificateBlob return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_getCertificateKeyAttributes (
	IN const pkcs11h_certificate_t certificate
) {
	CK_RV rv = CKR_OK;

	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;

	PKCS11H_ASSERT (certificate!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getCertificateKeyAttributes entry certificate=%p",
		(void *)certificate
	);

	certificate->maskSignMode = 0;

	while (rv == CKR_OK && !fOpSuccess) {
#if defined(ENABLE_PKCS11H_THREADING)
		PKCS11H_BOOL fMutexLocked = FALSE;
#endif
		CK_ATTRIBUTE key_attrs[] = {
			{CKA_SIGN, NULL, 0},
			{CKA_SIGN_RECOVER, NULL, 0}
		};

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&certificate->mutexCertificate)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		/*
		 * Don't try invalid object
		 */
		if (
			rv == CKR_OK &&
			certificate->hKey == PKCS11H_INVALID_OBJECT_HANDLE
		) {
			rv = CKR_OBJECT_HANDLE_INVALID;
		}

		if (rv == CKR_OK) {
			if (certificate->session->provider->maskSignMode != 0) {
				certificate->maskSignMode = certificate->session->provider->maskSignMode;
				fOpSuccess = TRUE;
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Key attributes enforced by provider (%08x)",
					certificate->maskSignMode
				);
			}
		}

		if (rv == CKR_OK && !fOpSuccess) {
			rv = _pkcs11h_getObjectAttributes (
				certificate->session,
				certificate->hKey,
				key_attrs,
				sizeof (key_attrs) / sizeof (CK_ATTRIBUTE)
			);
		}

		if (rv == CKR_OK && !fOpSuccess) {
			CK_BBOOL *key_attrs_sign = (CK_BBOOL *)key_attrs[0].pValue;
			CK_BBOOL *key_attrs_sign_recover = (CK_BBOOL *)key_attrs[1].pValue;

			if (key_attrs_sign != NULL && *key_attrs_sign != CK_FALSE) {
				certificate->maskSignMode |= PKCS11H_SIGNMODE_MASK_SIGN;
			}
			if (key_attrs_sign_recover != NULL && *key_attrs_sign_recover != CK_FALSE) {
				certificate->maskSignMode |= PKCS11H_SIGNMODE_MASK_RECOVER;
			}
			if (certificate->maskSignMode == 0) {
				rv = CKR_KEY_TYPE_INCONSISTENT;
			}
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Key attributes loaded (%08x)",
				certificate->maskSignMode
			);
		}

		_pkcs11h_freeObjectAttributes (
			key_attrs,
			sizeof (key_attrs) / sizeof (CK_ATTRIBUTE)
		);

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&certificate->mutexCertificate);
			fMutexLocked = FALSE;
		}
#endif
	
		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Get private key attributes failed: %ld:'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);

				rv = _pkcs11h_resetCertificateSession (
					certificate,
					FALSE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);

				fLoginRetry = TRUE;
			}
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_getCertificateKeyAttributes return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_validateCertificateSession (
	IN const pkcs11h_certificate_t certificate
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (certificate!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_validateCertificateSession entry certificate=%p",
		(void *)certificate
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_validateSession (certificate->session);
	}

	if (rv == CKR_OK) {
		if (certificate->hKey == PKCS11H_INVALID_OBJECT_HANDLE) {
			rv = CKR_OBJECT_HANDLE_INVALID;
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_validateCertificateSession return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
_pkcs11h_resetCertificateSession (
	IN const pkcs11h_certificate_t certificate,
	IN const PKCS11H_BOOL fPublicOnly,
	IN const unsigned maskPrompt
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	PKCS11H_BOOL fKeyValid = FALSE;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (certificate!=NULL);
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_resetCertificateSession entry certificate=%p, fPublicOnly=%d, maskPrompt=%08x",
		(void *)certificate,
		fPublicOnly ? 1 : 0,
		maskPrompt
	);

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&certificate->mutexCertificate)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		!fKeyValid &&
		rv == CKR_OK &&
		certificate->session == NULL &&
		(rv = _pkcs11h_getSessionByTokenId (certificate->id->token_id, &certificate->session)) == CKR_OK
	) {
		if (certificate->nPINCachePeriod != PKCS11H_PIN_CACHE_INFINITE) {
			if (certificate->session->nPINCachePeriod != PKCS11H_PIN_CACHE_INFINITE) {
				if (certificate->session->nPINCachePeriod > certificate->nPINCachePeriod) {
					certificate->session->timePINExpire = (
						certificate->session->timePINExpire -
						(time_t)certificate->session->nPINCachePeriod +
						(time_t)certificate->nPINCachePeriod
					);
					certificate->session->nPINCachePeriod = certificate->nPINCachePeriod;
				}
			}
			else {
				certificate->session->timePINExpire = (
					PKCS11H_TIME (NULL) +
					(time_t)certificate->nPINCachePeriod
				);
				certificate->session->nPINCachePeriod = certificate->nPINCachePeriod;
			}
		}	
	}

	/*
	 * First, if session seems to be valid
	 * and key handle is invalid (hard-set),
	 * try to fetch key handle,
	 * maybe the token is already logged in
	 */
	if (rv == CKR_OK) {
		if (
			certificate->session->hSession != PKCS11H_INVALID_SESSION_HANDLE && 
			certificate->hKey == PKCS11H_INVALID_OBJECT_HANDLE &&
			!fPublicOnly
		) {
			if (
				(rv = _pkcs11h_getObjectById (
					certificate->session,
					CKO_PRIVATE_KEY,
					certificate->id->attrCKA_ID,
					certificate->id->attrCKA_ID_size,
					&certificate->hKey
				)) == CKR_OK
			) {
				fKeyValid = TRUE;
			}
			else {
				/*
				 * Ignore error
				 */
				rv = CKR_OK;
				certificate->hKey = PKCS11H_INVALID_OBJECT_HANDLE;
			}
		}
	}

	if (
		!fKeyValid &&
		rv == CKR_OK &&
		(rv = _pkcs11h_login (
			certificate->session,
			fPublicOnly,
			TRUE,
			maskPrompt
		)) == CKR_OK
	) {
		rv = _pkcs11h_updateCertificateIdDescription (certificate->id);
	}

	if (
		!fKeyValid &&
		rv == CKR_OK &&
		!fPublicOnly &&
		(rv = _pkcs11h_getObjectById (
			certificate->session,
			CKO_PRIVATE_KEY,
			certificate->id->attrCKA_ID,
			certificate->id->attrCKA_ID_size,
			&certificate->hKey
		)) == CKR_OK
	) {
		fKeyValid = TRUE;
	}

	if (
		rv == CKR_OK &&
		!fPublicOnly &&
		!fKeyValid
	) {
		rv = CKR_FUNCTION_REJECTED;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&certificate->mutexCertificate);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_resetCertificateSession return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_certificate_private_op (
	IN const pkcs11h_certificate_t certificate,
	IN const enum _pkcs11h_private_op_e op,
	IN const CK_MECHANISM_TYPE mech_type,
	IN const unsigned char * const source,
	IN const size_t source_size,
	OUT unsigned char * const target,
	IN OUT size_t * const p_target_size
) {
	CK_MECHANISM mech = {
		mech_type, NULL, 0
	};
	
	CK_RV rv = CKR_OK;
	PKCS11H_BOOL fLoginRetry = FALSE;
	PKCS11H_BOOL fOpSuccess = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (source!=NULL);
	/*PKCS11H_ASSERT (target); NOT NEEDED*/
	PKCS11H_ASSERT (p_target_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_private_op entry certificate=%p, op=%d, mech_type=%ld, source=%p, source_size=%u, target=%p, p_target_size=%p",
		(void *)certificate,
		op,
		mech_type,
		source,
		source_size,
		target,
		(void *)p_target_size
	);

	if (target == NULL) {
		*p_target_size = 0;
	}

	while (rv == CKR_OK && !fOpSuccess) {
#if defined(ENABLE_PKCS11H_THREADING)
		PKCS11H_BOOL fMutexLocked = FALSE;
#endif

		if (rv == CKR_OK && !certificate->fOperationActive) {
			rv = _pkcs11h_validateCertificateSession (certificate);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&certificate->session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (rv == CKR_OK && !certificate->fOperationActive) {
			switch (op) {
				case _pkcs11h_private_op_sign:
					rv = certificate->session->provider->f->C_SignInit (
						certificate->session->hSession,
						&mech,
						certificate->hKey
					);
				break;
				case _pkcs11h_private_op_sign_recover:
					rv = certificate->session->provider->f->C_SignRecoverInit (
						certificate->session->hSession,
						&mech,
						certificate->hKey
					);
				break;
				case _pkcs11h_private_op_decrypt:
					rv = certificate->session->provider->f->C_DecryptInit (
						certificate->session->hSession,
						&mech,
						certificate->hKey
					);
				break;
				default:
					rv = CKR_ARGUMENTS_BAD;
				break;
			}
		}

		if (rv == CKR_OK) {
			CK_ULONG size = *p_target_size;

			switch (op) {
				case _pkcs11h_private_op_sign:
					rv = certificate->session->provider->f->C_Sign (
						certificate->session->hSession,
						(CK_BYTE_PTR)source,
						source_size,
						(CK_BYTE_PTR)target,
						&size
					);
				break;
				case _pkcs11h_private_op_sign_recover:
					rv = certificate->session->provider->f->C_SignRecover (
						certificate->session->hSession,
						(CK_BYTE_PTR)source,
						source_size,
						(CK_BYTE_PTR)target,
						&size
					);
				break;
				case _pkcs11h_private_op_decrypt:
					rv = certificate->session->provider->f->C_Decrypt (
						certificate->session->hSession,
						(CK_BYTE_PTR)source,
						source_size,
						(CK_BYTE_PTR)target,
						&size
					);
				break;
				default:
					rv = CKR_ARGUMENTS_BAD;
				break;
			}

			*p_target_size = size;
		}
		
		if (
			target == NULL &&
			(
				rv == CKR_BUFFER_TOO_SMALL ||
				rv == CKR_OK
			)
		) {
			certificate->fOperationActive = TRUE;
			rv = CKR_OK;
		}
		else {
			certificate->fOperationActive = FALSE;
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&certificate->session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Private key operation failed rv=%ld-'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);
				fLoginRetry = TRUE;
				rv = _pkcs11h_resetCertificateSession (
					certificate,
					FALSE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);
			}
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_private_op return rv=%ld-'%s', *p_target_size=%d",
		rv,
		pkcs11h_getMessage (rv),
		*p_target_size
	);
	
	return rv;
}

CK_RV
pkcs11h_freeCertificateId (
	IN pkcs11h_certificate_id_t certificate_id
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeCertificateId entry certificate_id=%p",
		(void *)certificate_id
	);

	if (certificate_id->attrCKA_ID != NULL) {
		_pkcs11h_free ((void *)&certificate_id->attrCKA_ID);
	}
	if (certificate_id->certificate_blob != NULL) {
		_pkcs11h_free ((void *)&certificate_id->certificate_blob);
	}
	if (certificate_id->token_id != NULL) {
		pkcs11h_freeTokenId (certificate_id->token_id);
		certificate_id->token_id = NULL;
	}
	_pkcs11h_free ((void *)&certificate_id);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeCertificateId return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_duplicateCertificateId (
	OUT pkcs11h_certificate_id_t * const to,
	IN const pkcs11h_certificate_id_t from
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (to!=NULL);
	PKCS11H_ASSERT (from!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_duplicateCertificateId entry to=%p form=%p",
		(void *)to,
		(void *)from
	);

	*to = NULL;

	if (rv == CKR_OK) {
		rv = _pkcs11h_dupmem (
			(void*)to,
			NULL,
			from,
			sizeof (struct pkcs11h_certificate_id_s)
		);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_dupmem (
			(void*)&(*to)->token_id,
			NULL,
			from->token_id,
			sizeof (struct pkcs11h_token_id_s)
		);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_dupmem (
			(void*)&(*to)->attrCKA_ID,
			&(*to)->attrCKA_ID_size,
			from->attrCKA_ID,
			from->attrCKA_ID_size
		);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_dupmem (
			(void*)&(*to)->certificate_blob,
			&(*to)->certificate_blob_size,
			from->certificate_blob,
			from->certificate_blob_size
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_duplicateCertificateId return rv=%ld-'%s', *to=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*to
	);
	
	return rv;
}

CK_RV
pkcs11h_freeCertificate (
	IN pkcs11h_certificate_t certificate
) {
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeCertificate entry certificate=%p",
		(void *)certificate
	);

	if (certificate != NULL) {
		if (certificate->session != NULL) {
			_pkcs11h_releaseSession (certificate->session);
		}
		pkcs11h_freeCertificateId (certificate->id);
		certificate->id = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
		_pkcs11h_mutexFree (&certificate->mutexCertificate);
#endif

		_pkcs11h_free ((void *)&certificate);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeCertificate return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_certificate_sign (
	IN const pkcs11h_certificate_t certificate,
	IN const CK_MECHANISM_TYPE mech_type,
	IN const unsigned char * const source,
	IN const size_t source_size,
	OUT unsigned char * const target,
	IN OUT size_t * const p_target_size
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (source!=NULL);
	/*PKCS11H_ASSERT (target); NOT NEEDED*/
	PKCS11H_ASSERT (p_target_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_sign entry certificate=%p, mech_type=%ld, source=%p, source_size=%u, target=%p, p_target_size=%p",
		(void *)certificate,
		mech_type,
		source,
		source_size,
		target,
		(void *)p_target_size
	);

	if (target == NULL) {
		*p_target_size = 0;
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_certificate_private_op (
			certificate,
			_pkcs11h_private_op_sign,
			mech_type,
			source,
			source_size,
			target,
			p_target_size
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_sign return rv=%ld-'%s', *p_target_size=%d",
		rv,
		pkcs11h_getMessage (rv),
		*p_target_size
	);
	
	return rv;
}

CK_RV
pkcs11h_certificate_signRecover (
	IN const pkcs11h_certificate_t certificate,
	IN const CK_MECHANISM_TYPE mech_type,
	IN const unsigned char * const source,
	IN const size_t source_size,
	OUT unsigned char * const target,
	IN OUT size_t * const p_target_size
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (source!=NULL);
	/*PKCS11H_ASSERT (target); NOT NEEDED*/
	PKCS11H_ASSERT (p_target_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_signRecover entry certificate=%p, mech_type=%ld, source=%p, source_size=%u, target=%p, p_target_size=%p",
		(void *)certificate,
		mech_type,
		source,
		source_size,
		target,
		(void *)p_target_size
	);

	if (target == NULL) {
		*p_target_size = 0;
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_certificate_private_op (
			certificate,
			_pkcs11h_private_op_sign_recover,
			mech_type,
			source,
			source_size,
			target,
			p_target_size
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_signRecover return rv=%ld-'%s', *p_target_size=%d",
		rv,
		pkcs11h_getMessage (rv),
		*p_target_size
	);

	return rv;
}

CK_RV
pkcs11h_certificate_signAny (
	IN const pkcs11h_certificate_t certificate,
	IN const CK_MECHANISM_TYPE mech_type,
	IN const unsigned char * const source,
	IN const size_t source_size,
	OUT unsigned char * const target,
	IN OUT size_t * const p_target_size
) {
	CK_RV rv = CKR_OK;
	PKCS11H_BOOL fSigned = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (source!=NULL);
	/*PKCS11H_ASSERT (target); NOT NEEDED*/
	PKCS11H_ASSERT (p_target_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_signAny entry certificate=%p, mech_type=%ld, source=%p, source_size=%u, target=%p, p_target_size=%p",
		(void *)certificate,
		mech_type,
		source,
		source_size,
		target,
		(void *)p_target_size
	);

	if (
		rv == CKR_OK &&
		certificate->maskSignMode == 0
	) {
		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Getting key attributes"
		);
		rv = _pkcs11h_getCertificateKeyAttributes (certificate);
	}

	if (
		rv == CKR_OK &&
		!fSigned &&
		(certificate->maskSignMode & PKCS11H_SIGNMODE_MASK_SIGN) != 0
	) {
		rv = pkcs11h_certificate_sign (
			certificate,
			mech_type,
			source,
			source_size,
			target,
			p_target_size
		);

		if (rv == CKR_OK) {
			fSigned = TRUE;
		}
		else if (
			rv == CKR_FUNCTION_NOT_SUPPORTED ||
			rv == CKR_KEY_FUNCTION_NOT_PERMITTED
		) {
			certificate->maskSignMode &= ~PKCS11H_SIGNMODE_MASK_SIGN;
			rv = CKR_OK;
		}
	}
	
	if (
		rv == CKR_OK &&
		!fSigned &&
		(certificate->maskSignMode & PKCS11H_SIGNMODE_MASK_RECOVER) != 0
	) {
		rv = pkcs11h_certificate_signRecover (
			certificate,
			mech_type,
			source,
			source_size,
			target,
			p_target_size
		);

		if (rv == CKR_OK) {
			fSigned = TRUE;
		}
		else if (
			rv == CKR_FUNCTION_NOT_SUPPORTED ||
			rv == CKR_KEY_FUNCTION_NOT_PERMITTED
		) {
			certificate->maskSignMode &= ~PKCS11H_SIGNMODE_MASK_RECOVER;
			rv = CKR_OK;
		}
	}

	if (!fSigned) {
		rv = CKR_FUNCTION_FAILED;
	}
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_signAny return rv=%ld-'%s', *p_target_size=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_target_size
	);

	return rv;
}

CK_RV
pkcs11h_certificate_decrypt (
	IN const pkcs11h_certificate_t certificate,
	IN const CK_MECHANISM_TYPE mech_type,
	IN const unsigned char * const source,
	IN const size_t source_size,
	OUT unsigned char * const target,
	IN OUT size_t * const p_target_size
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (source!=NULL);
	/*PKCS11H_ASSERT (target); NOT NEEDED*/
	PKCS11H_ASSERT (p_target_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_decrypt entry certificate=%p, mech_type=%ld, source=%p, source_size=%u, target=%p, p_target_size=%p",
		(void *)certificate,
		mech_type,
		source,
		source_size,
		target,
		(void *)p_target_size
	);

	if (target == NULL) {
		*p_target_size = 0;
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_certificate_private_op (
			certificate,
			_pkcs11h_private_op_decrypt,
			mech_type,
			source,
			source_size,
			target,
			p_target_size
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_decrypt return rv=%ld-'%s', *p_target_size=%d",
		rv,
		pkcs11h_getMessage (rv),
		*p_target_size
	);

	return rv;
}

CK_RV
pkcs11h_certificate_create (
	IN const pkcs11h_certificate_id_t certificate_id,
	IN const int nPINCachePeriod,
	OUT pkcs11h_certificate_t * const p_certificate
) {
	pkcs11h_certificate_t certificate = NULL;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (p_certificate!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_create entry certificate_id=%p, nPINCachePeriod=%d, p_certificate=%p",
		(void *)certificate_id,
		nPINCachePeriod,
		(void *)p_certificate
	);

	*p_certificate = NULL;

	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_malloc ((void*)&certificate, sizeof (struct pkcs11h_certificate_s))) == CKR_OK
	) {
		certificate->hKey = PKCS11H_INVALID_OBJECT_HANDLE;
		certificate->nPINCachePeriod = nPINCachePeriod;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (rv == CKR_OK) {
		rv = _pkcs11h_mutexInit (&certificate->mutexCertificate);
	}
#endif

	if (rv == CKR_OK) {
		rv = pkcs11h_duplicateCertificateId (&certificate->id, certificate_id);
	}

	if (rv == CKR_OK) {
		*p_certificate = certificate;
		certificate = NULL;
	}

	if (certificate != NULL) {
#if defined(ENABLE_PKCS11H_THREADING)
		_pkcs11h_mutexFree (&certificate->mutexCertificate);
#endif
		_pkcs11h_free ((void *)&certificate);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_create return rv=%ld-'%s' *p_certificate=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_certificate
	);
	
	return rv;
}

CK_RV
pkcs11h_certificate_getCertificateId (
	IN const pkcs11h_certificate_t certificate,
	OUT pkcs11h_certificate_id_t * const p_certificate_id
) {
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	PKCS11H_ASSERT (p_certificate_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_getCertificateId entry certificate=%p, certificate_id=%p",
		(void *)certificate,
		(void *)p_certificate_id
	);

	if (rv == CKR_OK) {
		rv = pkcs11h_duplicateCertificateId (
			p_certificate_id,
			certificate->id
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_getCertificateId return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_certificate_getCertificateBlob (
	IN const pkcs11h_certificate_t certificate,
	OUT unsigned char * const certificate_blob,
	IN OUT size_t * const p_certificate_blob_size
) {
	size_t certifiate_blob_size_max = 0;

	CK_RV rv = CKR_OK;
	
	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);
	/*PKCS11H_ASSERT (certificate_blob!=NULL); NOT NEEDED */
	PKCS11H_ASSERT (p_certificate_blob_size!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_getCertificateBlob entry certificate=%p, certificate_blob=%p, p_certificate_blob_size=%p",
		(void *)certificate,
		certificate_blob,
		(void *)p_certificate_blob_size
	);

	certifiate_blob_size_max = *p_certificate_blob_size;
	*p_certificate_blob_size = 0;

	if (rv == CKR_OK) {
		rv = _pkcs11h_ensureCertificateBlob (certificate);
	}

	if (rv == CKR_OK) {
		*p_certificate_blob_size = certificate->id->certificate_blob_size;
	}

	if (certificate_blob != NULL) {
		if (
			rv == CKR_OK &&
			certifiate_blob_size_max > certificate->id->certificate_blob_size
		) {
			rv = CKR_BUFFER_TOO_SMALL;
		}
	
		if (rv == CKR_OK) {
			memmove (
				certificate_blob,
				certificate->id->certificate_blob,
				*p_certificate_blob_size
			);
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_getCertificateBlob return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_certificate_ensureCertificateAccess (
	IN const pkcs11h_certificate_t certificate,
	IN const unsigned maskPrompt
) {
	PKCS11H_BOOL fValidCert = FALSE;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_ensureCertificateAccess entry certificate=%p, maskPrompt=%08x",
		(void *)certificate,
		maskPrompt
	);

	if (!fValidCert && rv == CKR_OK) {
		CK_OBJECT_HANDLE h = PKCS11H_INVALID_OBJECT_HANDLE;

		if (
			(rv = _pkcs11h_getObjectById (
				certificate->session,
				CKO_CERTIFICATE,
				certificate->id->attrCKA_ID,
				certificate->id->attrCKA_ID_size,
				&h
			)) == CKR_OK
		) {
			fValidCert = TRUE;
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot access existing object rv=%ld-'%s'",
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}
	}

	if (!fValidCert && rv == CKR_OK) {
		if (
			(rv = _pkcs11h_resetCertificateSession (
				certificate,
				TRUE,
				maskPrompt
			)) == CKR_OK
		) {
			fValidCert = TRUE;
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_ensureCertificateAccess return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);
	
	return rv;
}

CK_RV
pkcs11h_certificate_ensureKeyAccess (
	IN const pkcs11h_certificate_t certificate,
	IN const unsigned maskPrompt
) {
	CK_RV rv = CKR_OK;
	PKCS11H_BOOL fValidKey = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (certificate!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_ensureKeyAccess entry certificate=%p, maskPrompt=%08x",
		(void *)certificate,
		maskPrompt
	);

	if (!fValidKey && rv == CKR_OK) {
		if (
			(rv = _pkcs11h_getObjectById (
				certificate->session,
				CKO_PRIVATE_KEY,
				certificate->id->attrCKA_ID,
				certificate->id->attrCKA_ID_size,
				&certificate->hKey
			)) == CKR_OK
		) {
			fValidKey = TRUE;
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot access existing object rv=%ld-'%s'",
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
			certificate->hKey = PKCS11H_INVALID_OBJECT_HANDLE;
		}
	}

	if (!fValidKey && rv == CKR_OK) {
		if (
			(rv = _pkcs11h_resetCertificateSession (
				certificate,
				FALSE,
				maskPrompt
			)) == CKR_OK
		) {
			fValidKey = TRUE;
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_certificate_ensureKeyAccess return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);
	
	return rv;
}

#endif				/* ENABLE_PKCS11H_CERTIFICATE */

#if defined(ENABLE_PKCS11H_LOCATE)
/*======================================================================*
 * LOCATE INTERFACE
 *======================================================================*/

#if defined(ENABLE_PKCS11H_TOKEN) || defined(ENABLE_PKCS11H_CERTIFICATE)

static
CK_RV
_pkcs11h_locate_getTokenIdBySlotId (
	IN const char * const szSlot,
	OUT pkcs11h_token_id_t * const p_token_id
) {
	pkcs11h_provider_t current_provider = NULL;
	char szReferenceName[sizeof (((pkcs11h_provider_t)NULL)->szReferenceName)];

	CK_SLOT_ID selected_slot = PKCS11H_INVALID_SLOT_ID;
	CK_TOKEN_INFO info;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (szSlot!=NULL);
	PKCS11H_ASSERT (p_token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getTokenIdBySlotId entry szSlot='%s', p_token_id=%p",
		szSlot,
		(void *)p_token_id
	);

	*p_token_id = NULL;

	if (rv == CKR_OK) {
		if (strchr (szSlot, ':') == NULL) {
			szReferenceName[0] = '\0';
			selected_slot = atol (szSlot);
		}
		else {
			char *p;

			strncpy (szReferenceName, szSlot, sizeof (szReferenceName));
			szReferenceName[sizeof (szReferenceName)-1] = '\0';

			p = strchr (szReferenceName, ':');

			*p = '\0';
			p++;
			selected_slot = atol (p);
		}
	}
	
	if (rv == CKR_OK) {
		current_provider=s_pkcs11h_data->providers;
		while (
			current_provider != NULL &&
			szReferenceName[0] != '\0' &&		/* So first provider will be selected */
			strcmp (current_provider->szReferenceName, szReferenceName)
		) {
			current_provider = current_provider->next;
		}
	
		if (
			current_provider == NULL ||
			(
				current_provider != NULL &&
				!current_provider->fEnabled
			)
		) {
			rv = CKR_SLOT_ID_INVALID;
		}
	}

	if (
		rv == CKR_OK &&
		(rv = current_provider->f->C_GetTokenInfo (selected_slot, &info)) == CKR_OK
	) {
		rv = _pkcs11h_getTokenId (
			&info,
			p_token_id
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getTokenIdBySlotId return rv=%ld-'%s', *p_token_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_token_id
	);

	return rv;
}

static
CK_RV
_pkcs11h_locate_getTokenIdBySlotName (
	IN const char * const szName,
	OUT pkcs11h_token_id_t * const p_token_id
) {
	pkcs11h_provider_t current_provider = NULL;

	CK_SLOT_ID selected_slot = PKCS11H_INVALID_SLOT_ID;
	CK_TOKEN_INFO info;
	CK_RV rv = CKR_OK;

	PKCS11H_BOOL fFound = FALSE;

	PKCS11H_ASSERT (szName!=NULL);
	PKCS11H_ASSERT (p_token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getTokenIdBySlotName entry szName='%s', p_token_id=%p",
		szName,
		(void *)p_token_id
	);

	*p_token_id = NULL;

	current_provider = s_pkcs11h_data->providers;
	while (
		current_provider != NULL &&
		rv == CKR_OK &&
		!fFound
	) {
		CK_SLOT_ID_PTR slots = NULL;
		CK_ULONG slotnum;
		CK_SLOT_ID slot_index;

		if (!current_provider->fEnabled) {
			continue;
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_getSlotList (
				current_provider,
				CK_TRUE,
				&slots,
				&slotnum
			);
		}

		for (
			slot_index=0;
			(
				slot_index < slotnum &&
				rv == CKR_OK &&
				!fFound
			);
			slot_index++
		) {
			CK_SLOT_INFO info;

			if (
				(rv = current_provider->f->C_GetSlotInfo (
					slots[slot_index],
					&info
				)) == CKR_OK
			) {
				char szCurrentName[sizeof (info.slotDescription)+1];

				_pkcs11h_fixupFixedString (
					szCurrentName,
					(char *)info.slotDescription,
					sizeof (info.slotDescription)
				);

				if (!strcmp (szCurrentName, szName)) {
					fFound = TRUE;
					selected_slot = slots[slot_index];
				}
			}

			if (rv != CKR_OK) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Cannot get slot information for provider '%s' slot %ld rv=%ld-'%s'",
					current_provider->manufacturerID,
					slots[slot_index],
					rv,
					pkcs11h_getMessage (rv)
				);

				/*
				 * Ignore error
				 */
				rv = CKR_OK;
			}
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get slot list for provider '%s' rv=%ld-'%s'",
				current_provider->manufacturerID,
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		if (slots != NULL) {
			_pkcs11h_free ((void *)&slots);
			slots = NULL;
		}

		if (!fFound) {
			current_provider = current_provider->next;
		}
	}

	if (rv == CKR_OK && !fFound) {
		rv = CKR_SLOT_ID_INVALID;
	}

	if (
		rv == CKR_OK &&
		(rv = current_provider->f->C_GetTokenInfo (selected_slot, &info)) == CKR_OK
	) {
		rv = _pkcs11h_getTokenId (
			&info,
			p_token_id
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getTokenIdBySlotName return rv=%ld-'%s' *p_token_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_token_id
	);

	return rv; 
}

static
CK_RV
_pkcs11h_locate_getTokenIdByLabel (
	IN const char * const szLabel,
	OUT pkcs11h_token_id_t * const p_token_id
) {
	pkcs11h_provider_t current_provider = NULL;

	CK_SLOT_ID selected_slot = PKCS11H_INVALID_SLOT_ID;
	CK_TOKEN_INFO info;
	CK_RV rv = CKR_OK;

	PKCS11H_BOOL fFound = FALSE;

	PKCS11H_ASSERT (szLabel!=NULL);
	PKCS11H_ASSERT (p_token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getTokenIdByLabel entry szLabel='%s', p_token_id=%p",
		szLabel,
		(void *)p_token_id
	);

	*p_token_id = NULL;

	current_provider = s_pkcs11h_data->providers;
	while (
		current_provider != NULL &&
		rv == CKR_OK &&
		!fFound
	) {
		CK_SLOT_ID_PTR slots = NULL;
		CK_ULONG slotnum;
		CK_SLOT_ID slot_index;

		if (!current_provider->fEnabled) {
			continue;
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_getSlotList (
				current_provider,
				CK_TRUE,
				&slots,
				&slotnum
			);
		}

		for (
			slot_index=0;
			(
				slot_index < slotnum &&
				rv == CKR_OK &&
				!fFound
			);
			slot_index++
		) {
			CK_TOKEN_INFO info;

			if (rv == CKR_OK) {
				rv = current_provider->f->C_GetTokenInfo (
					slots[slot_index],
					&info
				);
			}

			if (rv == CKR_OK) {
				char szCurrentLabel[sizeof (info.label)+1];
		
				_pkcs11h_fixupFixedString (
					szCurrentLabel,
					(char *)info.label,
					sizeof (info.label)
				);

				if (!strcmp (szCurrentLabel, szLabel)) {
					fFound = TRUE;
					selected_slot = slots[slot_index];
				}
			}

			if (rv != CKR_OK) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Cannot get token information for provider '%s' slot %ld rv=%ld-'%s'",
					current_provider->manufacturerID,
					slots[slot_index],
					rv,
					pkcs11h_getMessage (rv)
				);

				/*
				 * Ignore error
				 */
				rv = CKR_OK;
			}
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get slot list for provider '%s' rv=%ld-'%s'",
				current_provider->manufacturerID,
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		if (slots != NULL) {
			_pkcs11h_free ((void *)&slots);
			slots = NULL;
		}

		if (!fFound) {
			current_provider = current_provider->next;
		}
	}

	if (rv == CKR_OK && !fFound) {
		rv = CKR_SLOT_ID_INVALID;
	}

	if (
		rv == CKR_OK &&
		(rv = current_provider->f->C_GetTokenInfo (selected_slot, &info)) == CKR_OK
	) {
		rv = _pkcs11h_getTokenId (
			&info,
			p_token_id
		);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getTokenIdByLabel return rv=%ld-'%s', *p_token_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_token_id
	);

	return rv;
}

CK_RV
pkcs11h_locate_token (
	IN const char * const szSlotType,
	IN const char * const szSlot,
	OUT pkcs11h_token_id_t * const p_token_id
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif

	pkcs11h_token_id_t dummy_token_id = NULL;
	pkcs11h_token_id_t token_id = NULL;
	PKCS11H_BOOL fFound = FALSE;
	
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (szSlotType!=NULL);
	PKCS11H_ASSERT (szSlot!=NULL);
	PKCS11H_ASSERT (p_token_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_locate_token entry szSlotType='%s', szSlot='%s', p_token_id=%p",
		szSlotType,
		szSlot,
		(void *)p_token_id
	);

	*p_token_id = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_newTokenId (&dummy_token_id)) == CKR_OK
	) {
		/*
		 * Temperary slot id
		 */
		strcpy (dummy_token_id->label, "SLOT(");
		strncat (dummy_token_id->label, szSlotType, sizeof (dummy_token_id->label)-1-strlen (dummy_token_id->label));
		strncat (dummy_token_id->label, "=", sizeof (dummy_token_id->label)-1-strlen (dummy_token_id->label));
		strncat (dummy_token_id->label, szSlot, sizeof (dummy_token_id->label)-1-strlen (dummy_token_id->label));
		strncat (dummy_token_id->label, ")", sizeof (dummy_token_id->label)-1-strlen (dummy_token_id->label));
		dummy_token_id->label[sizeof (dummy_token_id->label)-1] = 0;
	}

	while (rv == CKR_OK && !fFound) {
		if (!strcmp (szSlotType, "id")) {
			rv = _pkcs11h_locate_getTokenIdBySlotId (
				szSlot,
				&token_id
			);
		}
		else if (!strcmp (szSlotType, "name")) {
			rv = _pkcs11h_locate_getTokenIdBySlotName (
				szSlot,
				&token_id
			);
		}
		else if (!strcmp (szSlotType, "label")) {
			rv = _pkcs11h_locate_getTokenIdByLabel (
				szSlot,
				&token_id
			);
		}
		else {
			rv = CKR_ARGUMENTS_BAD;
		}

		if (rv == CKR_OK) {
			fFound = TRUE;
		}

		if (!fFound && rv != CKR_ARGUMENTS_BAD) {

			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: pkcs11h_locate_token failed rv=%ld-'%s'",
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;

			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Calling token_prompt hook for '%s'",
				dummy_token_id->label
			);
	
			if (
				!s_pkcs11h_data->hooks.token_prompt (
					s_pkcs11h_data->hooks.token_prompt_data,
					dummy_token_id
				)
			) {
				rv = CKR_CANCEL;
			}

			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: token_prompt returned %ld",
				rv
			);
		}
	}

	if (rv == CKR_OK && !fFound) {
		rv = CKR_SLOT_ID_INVALID;
	}

	if (rv == CKR_OK) {
		*p_token_id = token_id;
		token_id = NULL;
	}

	if (dummy_token_id != NULL) {
		pkcs11h_freeTokenId (dummy_token_id);
		dummy_token_id = NULL;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_locate_token return rv=%ld-'%s', *p_token_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_token_id
	);

	return rv;
}

#endif				/* ENABLE_PKCS11H_TOKEN || ENABLE_PKCS11H_CERTIFICATE */

#if defined(ENABLE_PKCS11H_CERTIFICATE)

static
void
_pkcs11h_locate_hexToBinary (
	OUT unsigned char * const target,
	IN const char * const szSource,
	IN OUT size_t * const p_target_size
) {
	size_t target_max_size;
	const char *p;
	char buf[3] = {'\0', '\0', '\0'};
	int i = 0;

	PKCS11H_ASSERT (szSource!=NULL);
	PKCS11H_ASSERT (target!=NULL);
	PKCS11H_ASSERT (p_target_size!=NULL);

	target_max_size = *p_target_size;
	p = szSource;
	*p_target_size = 0;

	while (*p != '\0' && *p_target_size < target_max_size) {
		if (isxdigit (*p)) {
			buf[i%2] = *p;

			if ((i%2) == 1) {
				unsigned v;
				if (sscanf (buf, "%x", &v) != 1) {
					v = 0;
				}
				target[*p_target_size] = v & 0xff;
				(*p_target_size)++;
			}

			i++;
		}
		p++;
	}
}

static
CK_RV
_pkcs11h_locate_getCertificateIdByLabel (
	IN const pkcs11h_session_t session,
	IN OUT const pkcs11h_certificate_id_t certificate_id,
	IN const char * const szLabel
) {
	CK_OBJECT_CLASS cert_filter_class = CKO_CERTIFICATE;
	CK_ATTRIBUTE cert_filter[] = {
		{CKA_CLASS, &cert_filter_class, sizeof (cert_filter_class)},
		{CKA_LABEL, (CK_BYTE_PTR)szLabel, strlen (szLabel)}
	};

	CK_OBJECT_HANDLE *objects = NULL;
	CK_ULONG objects_found = 0;
	CK_RV rv = CKR_OK;

	CK_ULONG i;

	PKCS11H_ASSERT (session!=NULL);
	PKCS11H_ASSERT (certificate_id!=NULL);
	PKCS11H_ASSERT (szLabel!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getCertificateIdByLabel entry session=%p, certificate_id=%p, szLabel='%s'",
		(void *)session,
		(void *)certificate_id,
		szLabel
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_validateSession (session);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_findObjects (
			session,
			cert_filter,
			sizeof (cert_filter) / sizeof (CK_ATTRIBUTE),
			&objects,
			&objects_found
		);
	}

	for (i=0;rv == CKR_OK && i < objects_found;i++) {
		CK_ATTRIBUTE attrs[] = {
			{CKA_ID, NULL, 0},
			{CKA_VALUE, NULL, 0}
		};

		if (rv == CKR_OK) {
			rv = _pkcs11h_getObjectAttributes (
				session,
				objects[i],
				attrs,
				sizeof (attrs) / sizeof (CK_ATTRIBUTE)
			);
		}

		if (
			rv == CKR_OK &&
			_pkcs11h_isBetterCertificate (
				certificate_id->certificate_blob,
				certificate_id->certificate_blob_size,
				attrs[1].pValue,
				attrs[1].ulValueLen
			)
		) {
			if (certificate_id->attrCKA_ID != NULL) {
				_pkcs11h_free ((void *)&certificate_id->attrCKA_ID);
			}
			if (certificate_id->certificate_blob != NULL) {
				_pkcs11h_free ((void *)&certificate_id->certificate_blob);
			}
			rv = _pkcs11h_dupmem (
				(void *)&certificate_id->attrCKA_ID,
				&certificate_id->attrCKA_ID_size,
				attrs[0].pValue,
				attrs[0].ulValueLen
			);
			rv = _pkcs11h_dupmem (
				(void *)&certificate_id->certificate_blob,
				&certificate_id->certificate_blob_size,
				attrs[1].pValue,
				attrs[1].ulValueLen
			);
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get object attribute for provider '%s' object %ld rv=%ld-'%s'",
				session->provider->manufacturerID,
				objects[i],
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		_pkcs11h_freeObjectAttributes (
			attrs,
			sizeof (attrs) / sizeof (CK_ATTRIBUTE)
		);
	}
	
	if (
		rv == CKR_OK &&
		certificate_id->certificate_blob == NULL
	) {
		rv = CKR_ATTRIBUTE_VALUE_INVALID;
	}

	if (objects != NULL) {
		_pkcs11h_free ((void *)&objects);
	}

	/*
	 * No need to free allocated objects
	 * on error, since the certificate_id
	 * should be free by caller.
	 */

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getCertificateIdByLabel return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_locate_getCertificateIdBySubject (
	IN const pkcs11h_session_t session,
	IN OUT const pkcs11h_certificate_id_t certificate_id,
	IN const char * const szSubject
) {
	CK_OBJECT_CLASS cert_filter_class = CKO_CERTIFICATE;
	CK_ATTRIBUTE cert_filter[] = {
		{CKA_CLASS, &cert_filter_class, sizeof (cert_filter_class)}
	};

	CK_OBJECT_HANDLE *objects = NULL;
	CK_ULONG objects_found = 0;
	CK_RV rv = CKR_OK;

	CK_ULONG i;

	PKCS11H_ASSERT (session!=NULL);
	PKCS11H_ASSERT (certificate_id!=NULL);
	PKCS11H_ASSERT (szSubject!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getCertificateIdBySubject entry session=%p, certificate_id=%p, szSubject=%s",
		(void *)session,
		(void *)certificate_id,
		szSubject
	);

	if (rv == CKR_OK) {
		rv = _pkcs11h_validateSession (session);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_findObjects (
			session,
			cert_filter,
			sizeof (cert_filter) / sizeof (CK_ATTRIBUTE),
			&objects,
			&objects_found
		);
	}

	for (i=0;rv == CKR_OK && i < objects_found;i++) {
		CK_ATTRIBUTE attrs[] = {
			{CKA_ID, NULL, 0},
			{CKA_VALUE, NULL, 0}
		};
		char szCurrentSubject[1024];
		szCurrentSubject[0] = '\0';

		if (rv == CKR_OK) {
			rv = _pkcs11h_getObjectAttributes (
				session,
				objects[i],
				attrs,
				sizeof (attrs) / sizeof (CK_ATTRIBUTE)
			);
		}

		if (rv == CKR_OK) {
			X509 *x509 = NULL;
			pkcs11_openssl_d2i_t d2i1;

			x509 = X509_new ();

			d2i1 = (pkcs11_openssl_d2i_t)attrs[1].pValue;
			if (d2i_X509 (&x509, &d2i1, attrs[1].ulValueLen)) {
				X509_NAME_oneline (
					X509_get_subject_name (x509),
					szCurrentSubject,
					sizeof (szCurrentSubject)
				);
				szCurrentSubject[sizeof (szCurrentSubject) - 1] = '\0';
			}

			if (x509 != NULL) {
				X509_free (x509);
				x509 = NULL;
			}
		}

		if (
			rv == CKR_OK &&
			!strcmp (szSubject, szCurrentSubject) &&
			_pkcs11h_isBetterCertificate (
				certificate_id->certificate_blob,
				certificate_id->certificate_blob_size,
				attrs[1].pValue,
				attrs[1].ulValueLen
			)
		) {
			if (certificate_id->attrCKA_ID != NULL) {
				_pkcs11h_free ((void *)&certificate_id->attrCKA_ID);
			}
			if (certificate_id->certificate_blob != NULL) {
				_pkcs11h_free ((void *)&certificate_id->certificate_blob);
			}
			rv = _pkcs11h_dupmem (
				(void *)&certificate_id->attrCKA_ID,
				&certificate_id->attrCKA_ID_size,
				attrs[0].pValue,
				attrs[0].ulValueLen
			);
			rv = _pkcs11h_dupmem (
				(void *)&certificate_id->certificate_blob,
				&certificate_id->certificate_blob_size,
				attrs[1].pValue,
				attrs[1].ulValueLen
			);
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get object attribute for provider '%s' object %ld rv=%ld-'%s'",
				session->provider->manufacturerID,
				objects[i],
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		_pkcs11h_freeObjectAttributes (
			attrs,
			sizeof (attrs) / sizeof (CK_ATTRIBUTE)
		);
	}
	
	if (
		rv == CKR_OK &&
		certificate_id->certificate_blob == NULL
	) {
		rv = CKR_ATTRIBUTE_VALUE_INVALID;
	}

	if (objects != NULL) {
		_pkcs11h_free ((void *)&objects);
	}

	/*
	 * No need to free allocated objects
	 * on error, since the certificate_id
	 * should be free by caller.
	 */

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_locate_getCertificateIdBySubject return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_locate_certificate (
	IN const char * const szSlotType,
	IN const char * const szSlot,
	IN const char * const szIdType,
	IN const char * const szId,
	OUT pkcs11h_certificate_id_t * const p_certificate_id
) {
	pkcs11h_certificate_id_t certificate_id = NULL;
	pkcs11h_session_t session = NULL;
	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;
	
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (szSlotType!=NULL);
	PKCS11H_ASSERT (szSlot!=NULL);
	PKCS11H_ASSERT (szIdType!=NULL);
	PKCS11H_ASSERT (szId!=NULL);
	PKCS11H_ASSERT (p_certificate_id!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_locateCertificate entry szSlotType='%s', szSlot='%s', szIdType='%s', szId='%s', p_certificate_id=%p",
		szSlotType,
		szSlot,
		szIdType,
		szId,
		(void *)p_certificate_id
	);

	*p_certificate_id = NULL;

	if (rv == CKR_OK) {
		rv = _pkcs11h_newCertificateId (&certificate_id);
	}

	if (rv == CKR_OK) {
		rv = pkcs11h_locate_token (
			szSlotType,
			szSlot,
			&certificate_id->token_id
		);
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_getSessionByTokenId (
			certificate_id->token_id,
			&session
		);
	}

	while (rv == CKR_OK && !fOpSuccess) {
#if defined(ENABLE_PKCS11H_THREADING)
		PKCS11H_BOOL fMutexLocked = FALSE;
#endif

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (!strcmp (szIdType, "id")) {
			certificate_id->attrCKA_ID_size = strlen (szId)/2;

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_malloc (
					(void*)&certificate_id->attrCKA_ID,
					certificate_id->attrCKA_ID_size
				)) == CKR_OK
			) {
				_pkcs11h_locate_hexToBinary (
					certificate_id->attrCKA_ID,
					szId,
					&certificate_id->attrCKA_ID_size
				);
			}
		}
		else if (!strcmp (szIdType, "label")) {
			rv = _pkcs11h_locate_getCertificateIdByLabel (
				session,
				certificate_id,
				szId
			);
		}
		else if (!strcmp (szIdType, "subject")) {
			rv = _pkcs11h_locate_getCertificateIdBySubject (
				session,
				certificate_id,
				szId
			);
		}
		else {
			rv = CKR_ARGUMENTS_BAD;
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
			fMutexLocked = FALSE;
		}
#endif

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Get certificate failed: %ld:'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);

				rv = _pkcs11h_login (
					session,
					TRUE,
					TRUE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);

				fLoginRetry = TRUE;
			}
		}
	}

	if (rv == CKR_OK) {
		*p_certificate_id = certificate_id;
		certificate_id = NULL;
	}

	if (certificate_id != NULL) {
		pkcs11h_freeCertificateId (certificate_id);
		certificate_id = NULL;
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_locateCertificate return rv=%ld-'%s' *p_certificate_id=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_certificate_id
	);
	
	return rv;
}

#endif				/* ENABLE_PKCS11H_CERTIFICATE */

#endif				/* ENABLE_PKCS11H_LOCATE */

#if defined(ENABLE_PKCS11H_ENUM)
/*======================================================================*
 * ENUM INTERFACE
 *======================================================================*/

#if defined(ENABLE_PKCS11H_TOKEN)

CK_RV
pkcs11h_freeTokenIdList (
	IN const pkcs11h_token_id_list_t token_id_list
) {
	pkcs11h_token_id_list_t _id = token_id_list;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	/*PKCS11H_ASSERT (token_id_list!=NULL); NOT NEEDED*/

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeTokenIdList entry token_id_list=%p",
		(void *)token_id_list
	);

	while (_id != NULL) {
		pkcs11h_token_id_list_t x = _id;
		_id = _id->next;
		if (x->token_id != NULL) {
			pkcs11h_freeTokenId (x->token_id);
		}
		x->next = NULL;
		_pkcs11h_free ((void *)&x);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeTokenIdList return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_enum_getTokenIds (
	IN const int method,
	OUT pkcs11h_token_id_list_t * const p_token_id_list
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif

	pkcs11h_token_id_list_t token_id_list = NULL;
	pkcs11h_provider_t current_provider;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (p_token_id_list!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enum_getTokenIds entry p_token_id_list=%p",
		(void *)p_token_id_list
	);

	*p_token_id_list = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexGlobal)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	for (
		current_provider = s_pkcs11h_data->providers;
		(
			current_provider != NULL &&
			rv == CKR_OK
		);
		current_provider = current_provider->next
	) {
		CK_SLOT_ID_PTR slots = NULL;
		CK_ULONG slotnum;
		CK_SLOT_ID slot_index;

		if (!current_provider->fEnabled) {
			continue;
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_getSlotList (
				current_provider,
				CK_TRUE,
				&slots,
				&slotnum
			);
		}

		for (
			slot_index=0;
			(
				slot_index < slotnum &&
				rv == CKR_OK
			);
			slot_index++
		) {
			pkcs11h_token_id_list_t entry = NULL;
			CK_TOKEN_INFO info;

			if (rv == CKR_OK) {
				rv = _pkcs11h_malloc ((void *)&entry, sizeof (struct pkcs11h_token_id_list_s));
			}

			if (rv == CKR_OK) {
				rv = current_provider->f->C_GetTokenInfo (
					slots[slot_index],
					&info
				);
			}

			if (rv == CKR_OK) {
				rv = _pkcs11h_getTokenId (
					&info,
					&entry->token_id
				);
			}

			if (rv == CKR_OK) {
				entry->next = token_id_list;
				token_id_list = entry;
				entry = NULL;
			}

			if (entry != NULL) {
				pkcs11h_freeTokenIdList (entry);
				entry = NULL;
			}
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get slot list for provider '%s' rv=%ld-'%s'",
				current_provider->manufacturerID,
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		if (slots != NULL) {
			_pkcs11h_free ((void *)&slots);
			slots = NULL;
		}
	}

	if (rv == CKR_OK && method == PKCS11H_ENUM_METHOD_CACHE) {
		pkcs11h_session_t session = NULL;

		for (
			session = s_pkcs11h_data->sessions;
			session != NULL && rv == CKR_OK;
			session = session->next
		) {
			pkcs11h_token_id_list_t entry = NULL;
			PKCS11H_BOOL fFound = FALSE;

			for (
				entry = token_id_list;
				entry != NULL && !fFound;
				entry = entry->next
			) {
				if (
					pkcs11h_sameTokenId (
						session->token_id,
						entry->token_id
					)
				) {
					fFound = TRUE;
				}
			}

			if (!fFound) {
				entry = NULL;

				if (rv == CKR_OK) {
					rv = _pkcs11h_malloc (
						(void *)&entry,
						sizeof (struct pkcs11h_token_id_list_s)
					);
				}

				if (rv == CKR_OK) {
					rv = pkcs11h_duplicateTokenId (
						&entry->token_id,
						session->token_id
					);
				}

				if (rv == CKR_OK) {
					entry->next = token_id_list;
					token_id_list = entry;
					entry = NULL;
				}

				if (entry != NULL) {
					if (entry->token_id != NULL) {
						pkcs11h_freeTokenId (entry->token_id);
					}
					_pkcs11h_free ((void *)&entry);
				}
			}
		}
	}

	if (rv == CKR_OK) {
		*p_token_id_list = token_id_list;
		token_id_list = NULL;
	}

	if (token_id_list != NULL) {
		pkcs11h_freeTokenIdList (token_id_list);
		token_id_list = NULL;
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		rv = _pkcs11h_mutexRelease (&s_pkcs11h_data->mutexGlobal);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enum_getTokenIds return rv=%ld-'%s', *p_token_id_list=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)p_token_id_list
	);
	
	return rv;
}

#endif

#if defined(ENABLE_PKCS11H_DATA)

CK_RV
pkcs11h_freeDataIdList (
	IN const pkcs11h_data_id_list_t data_id_list
) {
	pkcs11h_data_id_list_t _id = data_id_list;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	/*PKCS11H_ASSERT (data_id_list!=NULL); NOT NEEDED*/

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeDataIdList entry token_id_list=%p",
		(void *)data_id_list
	);

	while (_id != NULL) {
		pkcs11h_data_id_list_t x = _id;
		_id = _id->next;

		if (x->application != NULL) {
			_pkcs11h_free ((void *)&x->application);
		}
		if (x->label != NULL) {
			_pkcs11h_free ((void *)&x->label);
		}
		_pkcs11h_free ((void *)&x);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeDataIdList return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_enumDataObjects (
	IN const pkcs11h_token_id_t token_id,
	IN const PKCS11H_BOOL fPublic,
	OUT pkcs11h_data_id_list_t * const p_data_id_list
) {
	pkcs11h_session_t session = NULL;
	pkcs11h_data_id_list_t data_id_list = NULL;
	CK_RV rv = CKR_OK;

	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (p_data_id_list!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enumDataObjects entry p_data_id_list=%p",
		(void *)p_data_id_list
	);

	*p_data_id_list = NULL;

	if (rv == CKR_OK) {
		rv = _pkcs11h_getSessionByTokenId (
			token_id,
			&session
		);
	}

	while (rv == CKR_OK && !fOpSuccess) {
#if defined(ENABLE_PKCS11H_THREADING)
		PKCS11H_BOOL fMutexLocked = FALSE;
#endif

		CK_OBJECT_CLASS class = CKO_DATA;
		CK_ATTRIBUTE filter[] = {
			{CKA_CLASS, (void *)&class, sizeof (class)}
		};
		CK_OBJECT_HANDLE *objects = NULL;
		CK_ULONG objects_found = 0;

		CK_ULONG i;

		if (rv == CKR_OK) {
			rv = _pkcs11h_validateSession (session);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_mutexLock (&session->mutexSession)) == CKR_OK
		) {
			fMutexLocked = TRUE;
		}
#endif

		if (rv == CKR_OK) {
			rv = _pkcs11h_findObjects (
				session,
				filter,
				sizeof (filter) / sizeof (CK_ATTRIBUTE),
				&objects,
				&objects_found
			);
		}

		for (i = 0;rv == CKR_OK && i < objects_found;i++) {
			pkcs11h_data_id_list_t entry = NULL;

			CK_ATTRIBUTE attrs[] = {
				{CKA_APPLICATION, NULL, 0},
				{CKA_LABEL, NULL, 0}
			};

			if (rv == CKR_OK) {
				rv = _pkcs11h_getObjectAttributes (
					session,
					objects[i],
					attrs,
					sizeof (attrs) / sizeof (CK_ATTRIBUTE)
				);
			}
			
			if (rv == CKR_OK) {
				rv = _pkcs11h_malloc (
					(void *)&entry,
					sizeof (struct pkcs11h_data_id_list_s)
				);
			}

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_malloc (
					(void *)&entry->application,
					attrs[0].ulValueLen+1
				)) == CKR_OK
			) {
				memmove (entry->application, attrs[0].pValue, attrs[0].ulValueLen);
				entry->application[attrs[0].ulValueLen] = '\0';
			}

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_malloc (
					(void *)&entry->label,
					attrs[1].ulValueLen+1
				)) == CKR_OK
			) {
				memmove (entry->label, attrs[1].pValue, attrs[1].ulValueLen);
				entry->label[attrs[1].ulValueLen] = '\0';
			}

			if (rv == CKR_OK) {
				entry->next = data_id_list;
				data_id_list = entry;
				entry = NULL;
			}

			_pkcs11h_freeObjectAttributes (
				attrs,
				sizeof (attrs) / sizeof (CK_ATTRIBUTE)
			);

			if (entry != NULL) {
				if (entry->application != NULL) {
					_pkcs11h_free ((void *)&entry->application);
				}
				if (entry->label != NULL) {
					_pkcs11h_free ((void *)&entry->label);
				}
				_pkcs11h_free ((void *)&entry);
			}
		}

		if (objects != NULL) {
			_pkcs11h_free ((void *)&objects);
		}

#if defined(ENABLE_PKCS11H_THREADING)
		if (fMutexLocked) {
			_pkcs11h_mutexRelease (&session->mutexSession);
			fMutexLocked = FALSE;
		}
#endif

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Enumerate data objects failed rv=%ld-'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);
				fLoginRetry = TRUE;
				rv = _pkcs11h_login (
					session,
					fPublic,
					TRUE,
					(
						PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT |
						PKCS11H_PROMPT_MAST_ALLOW_CARD_PROMPT 
					)
				);
			}
		}
	}

	if (rv == CKR_OK) {
		*p_data_id_list = data_id_list;
		data_id_list = NULL;
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	if (data_id_list != NULL) {
		pkcs11h_freeDataIdList (data_id_list);
		data_id_list = NULL;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_data_id_list_t return rv=%ld-'%s', *p_data_id_list=%p",
		rv,
		pkcs11h_getMessage (rv),
		(void *)*p_data_id_list
	);
	
	return rv;
}

#endif				/* ENABLE_PKCS11H_DATA */

#if defined(ENABLE_PKCS11H_CERTIFICATE)

static
CK_RV
_pkcs11h_enum_getSessionCertificates (
	IN const pkcs11h_session_t session
) {
	PKCS11H_BOOL fOpSuccess = FALSE;
	PKCS11H_BOOL fLoginRetry = FALSE;

	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (session!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_enum_getSessionCertificates entry session=%p",
		(void *)session
	);
	
	/* THREADS: NO NEED TO LOCK, GLOBAL CACHE IS LOCKED */

	while (rv == CKR_OK && !fOpSuccess) {
		CK_OBJECT_CLASS cert_filter_class = CKO_CERTIFICATE;
		CK_ATTRIBUTE cert_filter[] = {
			{CKA_CLASS, &cert_filter_class, sizeof (cert_filter_class)}
		};

		CK_OBJECT_HANDLE *objects = NULL;
		CK_ULONG objects_found = 0;

		CK_ULONG i;

		if (rv == CKR_OK) {
			rv = _pkcs11h_validateSession (session);
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_findObjects (
				session,
				cert_filter,
				sizeof (cert_filter) / sizeof (CK_ATTRIBUTE),
				&objects,
				&objects_found
			);
		}
			
		for (i=0;rv == CKR_OK && i < objects_found;i++) {
			pkcs11h_certificate_id_t certificate_id = NULL;
			pkcs11h_certificate_id_list_t new_element = NULL;
			
			CK_ATTRIBUTE attrs[] = {
				{CKA_ID, NULL, 0},
				{CKA_VALUE, NULL, 0}
			};

			if (rv == CKR_OK) {
				rv = _pkcs11h_getObjectAttributes (
					session,
					objects[i],
					attrs,
					sizeof (attrs) / sizeof (CK_ATTRIBUTE)
				);
			}

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_newCertificateId (&certificate_id)) == CKR_OK
			) {
				rv = pkcs11h_duplicateTokenId (
					&certificate_id->token_id,
					session->token_id
				);
			}

			if (rv == CKR_OK) {
				rv = _pkcs11h_dupmem (
					(void*)&certificate_id->attrCKA_ID,
					&certificate_id->attrCKA_ID_size,
					attrs[0].pValue,
					attrs[0].ulValueLen
				);
			}

			if (rv == CKR_OK) {
				rv = _pkcs11h_dupmem (
					(void*)&certificate_id->certificate_blob,
					&certificate_id->certificate_blob_size,
					attrs[1].pValue,
					attrs[1].ulValueLen
				);
			}

			if (rv == CKR_OK) {
				rv = _pkcs11h_updateCertificateIdDescription (certificate_id);
			}

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_malloc (
					(void *)&new_element,
					sizeof (struct pkcs11h_certificate_id_list_s)
				)) == CKR_OK
			) {
				new_element->next = session->cached_certs;
				new_element->certificate_id = certificate_id;
				certificate_id = NULL;

				session->cached_certs = new_element;
				new_element = NULL;
			}

			if (certificate_id != NULL) {
				pkcs11h_freeCertificateId (certificate_id);
				certificate_id = NULL;
			}

			if (new_element != NULL) {
				_pkcs11h_free ((void *)&new_element);
				new_element = NULL;
			}

			_pkcs11h_freeObjectAttributes (
				attrs,
				sizeof (attrs) / sizeof (CK_ATTRIBUTE)
			);

			if (rv != CKR_OK) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Cannot get object attribute for provider '%s' object %ld rv=%ld-'%s'",
					session->provider->manufacturerID,
					objects[i],
					rv,
					pkcs11h_getMessage (rv)
				);

				/*
				 * Ignore error
				 */
				rv = CKR_OK;
			}
		}

		if (objects != NULL) {
			_pkcs11h_free ((void *)&objects);
		}

		if (rv == CKR_OK) {
			fOpSuccess = TRUE;
		}
		else {
			if (!fLoginRetry) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Get certificate attributes failed: %ld:'%s'",
					rv,
					pkcs11h_getMessage (rv)
				);

				rv = _pkcs11h_login (
					session,
					TRUE,
					TRUE,
					PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT
				);

				fLoginRetry = TRUE;
			}
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_enum_getSessionCertificates return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_enum_splitCertificateIdList (
	IN const pkcs11h_certificate_id_list_t cert_id_all,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_issuers_list,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_end_list
) {
	typedef struct info_s {
		struct info_s *next;
		pkcs11h_certificate_id_t e;
		X509 *x509;
		PKCS11H_BOOL fIsIssuer;
	} *info_t;

	pkcs11h_certificate_id_list_t cert_id_issuers_list = NULL;
	pkcs11h_certificate_id_list_t cert_id_end_list = NULL;

	info_t head = NULL;
	info_t info = NULL;

	CK_RV rv = CKR_OK;

	/*PKCS11H_ASSERT (cert_id_all!=NULL); NOT NEEDED */
	/*PKCS11H_ASSERT (p_cert_id_issuers_list!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (p_cert_id_end_list!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_splitCertificateIdList entry cert_id_all=%p, p_cert_id_issuers_list=%p, p_cert_id_end_list=%p",
		(void *)cert_id_all,
		(void *)p_cert_id_issuers_list,
		(void *)p_cert_id_end_list
	);

	if (p_cert_id_issuers_list != NULL) {
		*p_cert_id_issuers_list = NULL;
	}
	*p_cert_id_end_list = NULL;

	OpenSSL_add_all_digests ();

	if (rv == CKR_OK) {
		pkcs11h_certificate_id_list_t entry = NULL;

		for (
			entry = cert_id_all;
			entry != NULL && rv == CKR_OK;
			entry = entry->next
		) {
			info_t new_info = NULL;

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_malloc ((void *)&new_info, sizeof (struct info_s))) == CKR_OK &&
				entry->certificate_id->certificate_blob != NULL
			) {
				pkcs11_openssl_d2i_t d2i = (pkcs11_openssl_d2i_t)entry->certificate_id->certificate_blob;
				new_info->next = head;
				new_info->e = entry->certificate_id;
				new_info->x509 = X509_new ();
				if (
					new_info->x509 != NULL &&
					!d2i_X509 (
						&new_info->x509,
						&d2i,
						entry->certificate_id->certificate_blob_size
					)
				) {
					X509_free (new_info->x509);
					new_info->x509 = NULL;
				}
				head = new_info;
				new_info = NULL;
			}
		}

	}

	if (rv == CKR_OK) {
		for (
			info = head;
			info != NULL;
			info = info->next
		) {
			info_t info2 = NULL;
			for (
				info2 = head;
				info2 != NULL && !info->fIsIssuer;
				info2 = info2->next
			) {
				EVP_PKEY *pub = NULL;

				pub = X509_get_pubkey (info->x509);

				if (
					info != info2 &&
					info->x509 != NULL &&
					info2->x509 != NULL &&
/* Some people get this wrong		!X509_NAME_cmp (
						X509_get_subject_name (info->x509),
						X509_get_issuer_name (info2->x509)
					) && */
					X509_verify (info2->x509, pub) == 1
				) {
					info->fIsIssuer = TRUE;
				}

				if (pub != NULL) {
					EVP_PKEY_free (pub);
					pub = NULL;
				}
			}
		}
	}

	if (rv == CKR_OK) {
		for (
			info = head;
			info != NULL && rv == CKR_OK;
			info = info->next
		) {
			pkcs11h_certificate_id_list_t new_entry = NULL;

			if (rv == CKR_OK) {
				rv = _pkcs11h_malloc (
					(void *)&new_entry,
					sizeof (struct pkcs11h_certificate_id_list_s)
				);
			}

			if (
				rv == CKR_OK &&
				(rv = pkcs11h_duplicateCertificateId (
					&new_entry->certificate_id,
					info->e
				)) == CKR_OK
			) {
				/*
				 * Should not free base list
				 */
				info->e = NULL;
			}

			if (rv == CKR_OK) {
				if (info->fIsIssuer) {
					new_entry->next = cert_id_issuers_list;
					cert_id_issuers_list = new_entry;
					new_entry = NULL;
				}
				else {
					new_entry->next = cert_id_end_list;
					cert_id_end_list = new_entry;
					new_entry = NULL;
				}
			}

			if (new_entry != NULL) {
				if (new_entry->certificate_id != NULL) {
					pkcs11h_freeCertificateId (new_entry->certificate_id);
				}
				_pkcs11h_free ((void *)&new_entry);
			}
		}
	}

	if (rv == CKR_OK) {
		while (head != NULL) {
			info_t entry = head;
			head = head->next;

			if (entry->x509 != NULL) {
				X509_free (entry->x509);
				entry->x509 = NULL;
			}
			_pkcs11h_free ((void *)&entry);
		}
	}

	if (rv == CKR_OK && p_cert_id_issuers_list != NULL ) {
		*p_cert_id_issuers_list = cert_id_issuers_list;
		cert_id_issuers_list = NULL;
	}

	if (rv == CKR_OK) {
		*p_cert_id_end_list = cert_id_end_list;
		cert_id_end_list = NULL;
	}

	if (cert_id_issuers_list != NULL) {
		pkcs11h_freeCertificateIdList (cert_id_issuers_list);
	}

	if (cert_id_end_list != NULL) {
		pkcs11h_freeCertificateIdList (cert_id_end_list);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_splitCertificateIdList return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

CK_RV
pkcs11h_freeCertificateIdList (
	IN const pkcs11h_certificate_id_list_t cert_id_list
) {
	pkcs11h_certificate_id_list_t _id = cert_id_list;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	/*PKCS11H_ASSERT (cert_id_list!=NULL); NOT NEEDED*/

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeCertificateIdList entry cert_id_list=%p",
		(void *)cert_id_list
	);

	while (_id != NULL) {
		pkcs11h_certificate_id_list_t x = _id;
		_id = _id->next;
		if (x->certificate_id != NULL) {
			pkcs11h_freeCertificateId (x->certificate_id);
		}
		x->next = NULL;
		_pkcs11h_free ((void *)&x);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_freeCertificateIdList return"
	);

	return CKR_OK;
}

CK_RV
pkcs11h_enum_getTokenCertificateIds (
	IN const pkcs11h_token_id_t token_id,
	IN const int method,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_issuers_list,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_end_list
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	pkcs11h_session_t session = NULL;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	PKCS11H_ASSERT (token_id!=NULL);
	/*PKCS11H_ASSERT (p_cert_id_issuers_list!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (p_cert_id_end_list!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enum_getTokenCertificateIds entry token_id=%p, method=%d, p_cert_id_issuers_list=%p, p_cert_id_end_list=%p",
		(void *)token_id,
		method,
		(void *)p_cert_id_issuers_list,
		(void *)p_cert_id_end_list
	);

	if (p_cert_id_issuers_list != NULL) {
		*p_cert_id_issuers_list = NULL;
	}
	*p_cert_id_end_list = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexCache)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_getSessionByTokenId (
			token_id,
			&session
		)) == CKR_OK
	) {
		if (method == PKCS11H_ENUM_METHOD_RELOAD) {
			pkcs11h_freeCertificateIdList (session->cached_certs);
			session->cached_certs = NULL;
		}

		if (session->cached_certs == NULL) {
			rv = _pkcs11h_enum_getSessionCertificates (session);
		}
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_enum_splitCertificateIdList (
			session->cached_certs,
			p_cert_id_issuers_list,
			p_cert_id_end_list
		);
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
	}

#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexCache);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enum_getTokenCertificateIds return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);
	
	return rv;
}

CK_RV
pkcs11h_enum_getCertificateIds (
	IN const int method,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_issuers_list,
	OUT pkcs11h_certificate_id_list_t * const p_cert_id_end_list
) {
#if defined(ENABLE_PKCS11H_THREADING)
	PKCS11H_BOOL fMutexLocked = FALSE;
#endif
	pkcs11h_certificate_id_list_t cert_id_list = NULL;
	pkcs11h_provider_t current_provider;
	pkcs11h_session_t current_session;
	CK_RV rv = CKR_OK;

	PKCS11H_ASSERT (s_pkcs11h_data!=NULL);
	PKCS11H_ASSERT (s_pkcs11h_data->fInitialized);
	/*PKCS11H_ASSERT (p_cert_id_issuers_list!=NULL); NOT NEEDED*/
	PKCS11H_ASSERT (p_cert_id_end_list!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enum_getCertificateIds entry method=%d, p_cert_id_issuers_list=%p, p_cert_id_end_list=%p",
		method,
		(void *)p_cert_id_issuers_list,
		(void *)p_cert_id_end_list
	);

	if (p_cert_id_issuers_list != NULL) {
		*p_cert_id_issuers_list = NULL;
	}
	*p_cert_id_end_list = NULL;

#if defined(ENABLE_PKCS11H_THREADING)
	if (
		rv == CKR_OK &&
		(rv = _pkcs11h_mutexLock (&s_pkcs11h_data->mutexCache)) == CKR_OK
	) {
		fMutexLocked = TRUE;
	}
#endif

	for (
		current_session = s_pkcs11h_data->sessions;
		current_session != NULL;
		current_session = current_session->next
	) {
		current_session->fTouch = FALSE;
		if (method == PKCS11H_ENUM_METHOD_RELOAD) {
			pkcs11h_freeCertificateIdList (current_session->cached_certs);
			current_session->cached_certs = NULL;
		}
	}

	for (
		current_provider = s_pkcs11h_data->providers;
		(
			current_provider != NULL &&
			rv == CKR_OK
		);
		current_provider = current_provider->next
	) {
		CK_SLOT_ID_PTR slots = NULL;
		CK_ULONG slotnum;
		CK_SLOT_ID slot_index;

		if (!current_provider->fEnabled) {
			continue;
		}

		if (rv == CKR_OK) {
			rv = _pkcs11h_getSlotList (
				current_provider,
				CK_TRUE,
				&slots,
				&slotnum
			);
		}

		for (
			slot_index=0;
			(
				slot_index < slotnum &&
				rv == CKR_OK
			);
			slot_index++
		) {
			pkcs11h_session_t session = NULL;
			pkcs11h_token_id_t token_id = NULL;
			CK_TOKEN_INFO info;

			if (rv == CKR_OK) {
				rv = current_provider->f->C_GetTokenInfo (
					slots[slot_index],
					&info
				);
			}

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_getTokenId (
					&info,
					&token_id
				)) == CKR_OK &&
				(rv = _pkcs11h_getSessionByTokenId (
					token_id,
					&session
				)) == CKR_OK
			) {
				session->fTouch = TRUE;

				if (session->cached_certs == NULL) {
					rv = _pkcs11h_enum_getSessionCertificates (session);
				}
			}

			if (rv != CKR_OK) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Cannot get token information for provider '%s' slot %ld rv=%ld-'%s'",
					current_provider->manufacturerID,
					slots[slot_index],
					rv,
					pkcs11h_getMessage (rv)
				);

				/*
				 * Ignore error
				 */
				rv = CKR_OK;
			}

			if (session != NULL) {
				_pkcs11h_releaseSession (session);
				session = NULL;
			}

			if (token_id != NULL) {
				pkcs11h_freeTokenId (token_id);
				token_id = NULL;
			}
		}

		if (rv != CKR_OK) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Cannot get slot list for provider '%s' rv=%ld-'%s'",
				current_provider->manufacturerID,
				rv,
				pkcs11h_getMessage (rv)
			);

			/*
			 * Ignore error
			 */
			rv = CKR_OK;
		}

		if (slots != NULL) {
			_pkcs11h_free ((void *)&slots);
			slots = NULL;
		}
	}

	for (
		current_session = s_pkcs11h_data->sessions;
		(
			current_session != NULL &&
			rv == CKR_OK
		);
		current_session = current_session->next
	) {
		if (
			method == PKCS11H_ENUM_METHOD_CACHE ||
			(
				(
					method == PKCS11H_ENUM_METHOD_RELOAD ||
					method == PKCS11H_ENUM_METHOD_CACHE_EXIST
				) &&
				current_session->fTouch
			)
		) {
			pkcs11h_certificate_id_list_t entry = NULL;

			for (
				entry = current_session->cached_certs;
				(
					entry != NULL &&
					rv == CKR_OK
				);
				entry = entry->next
			) {
				pkcs11h_certificate_id_list_t new_entry = NULL;

				if (
					rv == CKR_OK &&
					(rv = _pkcs11h_malloc (
						(void *)&new_entry,
						sizeof (struct pkcs11h_certificate_id_list_s)
					)) == CKR_OK &&
					(rv = pkcs11h_duplicateCertificateId (
						&new_entry->certificate_id,
						entry->certificate_id
					)) == CKR_OK
				) {
					new_entry->next = cert_id_list;
					cert_id_list = new_entry;
					new_entry = NULL;
				}

				if (new_entry != NULL) {
					new_entry->next = NULL;
					pkcs11h_freeCertificateIdList (new_entry);
					new_entry = NULL;
				}
			}
		}
	}

	if (rv == CKR_OK) {
		rv = _pkcs11h_enum_splitCertificateIdList (
			cert_id_list,
			p_cert_id_issuers_list,
			p_cert_id_end_list
		);
	}

	if (cert_id_list != NULL) {
		pkcs11h_freeCertificateIdList (cert_id_list);
		cert_id_list = NULL;
	}


#if defined(ENABLE_PKCS11H_THREADING)
	if (fMutexLocked) {
		_pkcs11h_mutexRelease (&s_pkcs11h_data->mutexCache);
		fMutexLocked = FALSE;
	}
#endif

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_enum_getCertificateIds return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);
	
	return rv;
}

#endif				/* ENABLE_PKCS11H_CERTIFICATE */

#endif				/* ENABLE_PKCS11H_ENUM */

#if defined(ENABLE_PKCS11H_SLOTEVENT)
/*======================================================================*
 * SLOTEVENT INTERFACE
 *======================================================================*/

static
unsigned long
_pkcs11h_slotevent_checksum (
	IN const unsigned char * const p,
	IN const size_t s
) {
	unsigned long r = 0;
	size_t i;
	for (i=0;i<s;i++) {
		r += p[i];
	}
	return r;
}

static
void *
_pkcs11h_slotevent_provider (
	IN void *p
) {
	pkcs11h_provider_t provider = (pkcs11h_provider_t)p;
	CK_SLOT_ID slot;
	CK_RV rv = CKR_OK;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_provider provider='%s' entry",
		provider->manufacturerID
	);

	if (rv == CKR_OK && !provider->fEnabled) {
		rv = CKR_OPERATION_NOT_INITIALIZED;
	}

	if (rv == CKR_OK) {

		if (provider->nSlotEventPollInterval == 0) {
			provider->nSlotEventPollInterval = PKCS11H_DEFAULT_SLOTEVENT_POLL;
		}

		/*
		 * If we cannot finalize, we cannot cause
		 * WaitForSlotEvent to terminate
		 */
		if (!provider->fShouldFinalize) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Setup slotevent provider='%s' mode hardset to poll",
				provider->manufacturerID
			);
			provider->nSlotEventMethod = PKCS11H_SLOTEVENT_METHOD_POLL;
		}

		if (
			provider->nSlotEventMethod == PKCS11H_SLOTEVENT_METHOD_AUTO ||
			provider->nSlotEventMethod == PKCS11H_SLOTEVENT_METHOD_TRIGGER
		) { 
			if (
				provider->f->C_WaitForSlotEvent (
					CKF_DONT_BLOCK,
					&slot,
					NULL_PTR
				) == CKR_FUNCTION_NOT_SUPPORTED
			) {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Setup slotevent provider='%s' mode is poll",
					provider->manufacturerID
				);

				provider->nSlotEventMethod = PKCS11H_SLOTEVENT_METHOD_POLL;
			}
			else {
				PKCS11H_DEBUG (
					PKCS11H_LOG_DEBUG1,
					"PKCS#11: Setup slotevent provider='%s' mode is trigger",
					provider->manufacturerID
				);

				provider->nSlotEventMethod = PKCS11H_SLOTEVENT_METHOD_TRIGGER;
			}
		}
	}

	if (provider->nSlotEventMethod == PKCS11H_SLOTEVENT_METHOD_TRIGGER) {
		while (
			!s_pkcs11h_data->fSlotEventShouldTerminate &&
			provider->fEnabled &&
			rv == CKR_OK &&
			(rv = provider->f->C_WaitForSlotEvent (
				0,
				&slot,
				NULL_PTR
			)) == CKR_OK
		) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Slotevent provider='%s' event",
				provider->manufacturerID
			);

			_pkcs11h_condSignal (&s_pkcs11h_data->condSlotEvent);
		}
	}
	else {
		unsigned long ulLastChecksum = 0;
		PKCS11H_BOOL fFirstTime = TRUE;

		while (
			!s_pkcs11h_data->fSlotEventShouldTerminate &&
			provider->fEnabled &&
			rv == CKR_OK
		) {
			unsigned long ulCurrentChecksum = 0;

			CK_SLOT_ID_PTR slots = NULL;
			CK_ULONG slotnum;

			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Slotevent provider='%s' poll",
				provider->manufacturerID
			);

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_getSlotList (
					provider,
					TRUE,
					&slots,
					&slotnum
				)) == CKR_OK
			) {
				CK_ULONG i;
				
				for (i=0;i<slotnum;i++) {
					CK_TOKEN_INFO info;

					if (provider->f->C_GetTokenInfo (slots[i], &info) == CKR_OK) {
						ulCurrentChecksum += (
							_pkcs11h_slotevent_checksum (
								info.label,
								sizeof (info.label)
							) +
							_pkcs11h_slotevent_checksum (
								info.manufacturerID,
								sizeof (info.manufacturerID)
							) +
							_pkcs11h_slotevent_checksum (
								info.model,
								sizeof (info.model)
							) +
							_pkcs11h_slotevent_checksum (
								info.serialNumber,
								sizeof (info.serialNumber)
							)
						);
					}
				}
			}
			
			if (rv == CKR_OK) {
				if (fFirstTime) {
					fFirstTime = FALSE;
				}
				else {
					if (ulLastChecksum != ulCurrentChecksum) {
						PKCS11H_DEBUG (
							PKCS11H_LOG_DEBUG1,
							"PKCS#11: Slotevent provider='%s' event",
							provider->manufacturerID
						);

						_pkcs11h_condSignal (&s_pkcs11h_data->condSlotEvent);
					}
				}
				ulLastChecksum = ulCurrentChecksum;
			}

			if (slots != NULL) {
				_pkcs11h_free ((void *)&slots);
			}
			
			if (!s_pkcs11h_data->fSlotEventShouldTerminate) {
				_pkcs11h_sleep (provider->nSlotEventPollInterval);
			}
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_provider provider='%s' return",
		provider->manufacturerID
	);

	return NULL;
}

static
void *
_pkcs11h_slotevent_manager (
	IN void *p
) {
	PKCS11H_BOOL fFirst = TRUE;

	(void)p;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_manager entry"
	);

	/*
	 * Trigger hook, so application may
	 * depend on initial slot change
	 */
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG1,
		"PKCS#11: Calling slotevent hook"
	);
	s_pkcs11h_data->hooks.slotevent (s_pkcs11h_data->hooks.slotevent_data);

	while (
		fFirst ||	/* Must enter wait or mutex will never be free */
		!s_pkcs11h_data->fSlotEventShouldTerminate
	) {
		pkcs11h_provider_t current_provider;

		fFirst = FALSE;

		/*
		 * Start each provider thread
		 * if not already started.
		 * This is required in order to allow
		 * adding new providers.
		 */
		for (
			current_provider = s_pkcs11h_data->providers;
			current_provider != NULL;
			current_provider = current_provider->next
		) {
			if (!current_provider->fEnabled) {
				if (current_provider->threadSlotEvent == PKCS11H_THREAD_NULL) {
					_pkcs11h_threadStart (
						&current_provider->threadSlotEvent,
						_pkcs11h_slotevent_provider,
						current_provider
					);
				}
			}
			else {
				if (current_provider->threadSlotEvent != PKCS11H_THREAD_NULL) {
					_pkcs11h_threadJoin (&current_provider->threadSlotEvent);
				}
			}
		}

		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG2,
			"PKCS#11: _pkcs11h_slotevent_manager waiting for slotevent"
		);
		_pkcs11h_condWait (&s_pkcs11h_data->condSlotEvent, PKCS11H_COND_INFINITE);

		if (s_pkcs11h_data->fSlotEventSkipEvent) {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Slotevent skipping event"
			);
			s_pkcs11h_data->fSlotEventSkipEvent = FALSE;
		}
		else {
			PKCS11H_DEBUG (
				PKCS11H_LOG_DEBUG1,
				"PKCS#11: Calling slotevent hook"
			);
			s_pkcs11h_data->hooks.slotevent (s_pkcs11h_data->hooks.slotevent_data);
		}
	}

	{
		pkcs11h_provider_t current_provider;

		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG2,
			"PKCS#11: _pkcs11h_slotevent_manager joining threads"
		);


		for (
			current_provider = s_pkcs11h_data->providers;
			current_provider != NULL;
			current_provider = current_provider->next
		) {
			if (current_provider->threadSlotEvent != PKCS11H_THREAD_NULL) {
				_pkcs11h_threadJoin (&current_provider->threadSlotEvent);
			}
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_manager return"
	);

	return NULL;
}

static
CK_RV
_pkcs11h_slotevent_init () {
	CK_RV rv = CKR_OK;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_init entry"
	);

	if (!s_pkcs11h_data->fSlotEventInitialized) {
		if (rv == CKR_OK) {
			rv = _pkcs11h_condInit (&s_pkcs11h_data->condSlotEvent);
		}
		
		if (rv == CKR_OK) {
			rv = _pkcs11h_threadStart (
				&s_pkcs11h_data->threadSlotEvent,
				_pkcs11h_slotevent_manager,
				NULL
			);
		}
		
		if (rv == CKR_OK) {
			s_pkcs11h_data->fSlotEventInitialized = TRUE;
		}
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_init return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv;
}

static
CK_RV
_pkcs11h_slotevent_notify () {
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_notify entry"
	);

	if (s_pkcs11h_data->fSlotEventInitialized) {
		s_pkcs11h_data->fSlotEventSkipEvent = TRUE;
		_pkcs11h_condSignal (&s_pkcs11h_data->condSlotEvent);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_notify return"
	);

	return CKR_OK;
}

static
CK_RV
_pkcs11h_slotevent_terminate () {
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_terminate entry"
	);

	if (s_pkcs11h_data->fSlotEventInitialized) {
		s_pkcs11h_data->fSlotEventShouldTerminate = TRUE;

		_pkcs11h_slotevent_notify ();

		if (s_pkcs11h_data->threadSlotEvent != PKCS11H_THREAD_NULL) {
			_pkcs11h_threadJoin (&s_pkcs11h_data->threadSlotEvent);
		}

		_pkcs11h_condFree (&s_pkcs11h_data->condSlotEvent);
		s_pkcs11h_data->fSlotEventInitialized = FALSE;
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_slotevent_terminate return"
	);

	return CKR_OK;
}

#endif

#if defined(ENABLE_PKCS11H_OPENSSL)
/*======================================================================*
 * OPENSSL INTERFACE
 *======================================================================*/

static
pkcs11h_openssl_session_t
_pkcs11h_openssl_get_openssl_session (
	IN OUT const RSA *rsa
) {
	pkcs11h_openssl_session_t session;
		
	PKCS11H_ASSERT (rsa!=NULL);
#if OPENSSL_VERSION_NUMBER < 0x00907000L
	session = (pkcs11h_openssl_session_t)RSA_get_app_data ((RSA *)rsa);
#else
	session = (pkcs11h_openssl_session_t)RSA_get_app_data (rsa);
#endif
	PKCS11H_ASSERT (session!=NULL);

	return session;
}

static
pkcs11h_certificate_t
_pkcs11h_openssl_get_pkcs11h_certificate (
	IN OUT const RSA *rsa
) {
	pkcs11h_openssl_session_t session = _pkcs11h_openssl_get_openssl_session (rsa);
	
	PKCS11H_ASSERT (session!=NULL);
	PKCS11H_ASSERT (session->certificate!=NULL);

	return session->certificate;
}

#if OPENSSL_VERSION_NUMBER < 0x00907000L
static
int
_pkcs11h_openssl_dec (
	IN int flen,
	IN unsigned char *from,
	OUT unsigned char *to,
	IN OUT RSA *rsa,
	IN int padding
) {
#else
static
int
_pkcs11h_openssl_dec (
	IN int flen,
	IN const unsigned char *from,
	OUT unsigned char *to,
	IN OUT RSA *rsa,
	IN int padding
) {
#endif
	PKCS11H_ASSERT (from!=NULL);
	PKCS11H_ASSERT (to!=NULL);
	PKCS11H_ASSERT (rsa!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_openssl_dec entered - flen=%d, from=%p, to=%p, rsa=%p, padding=%d",
		flen,
		from,
		to,
		(void *)rsa,
		padding
	);

	PKCS11H_LOG (
		PKCS11H_LOG_ERROR,
		"PKCS#11: Private key decryption is not supported"
	);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_openssl_dec return"
	);

	return -1;
}

#if OPENSSL_VERSION_NUMBER < 0x00907000L
static
int
_pkcs11h_openssl_sign (
	IN int type,
	IN unsigned char *m,
	IN unsigned int m_len,
	OUT unsigned char *sigret,
	OUT unsigned int *siglen,
	IN OUT RSA *rsa
) {
#else
static
int
_pkcs11h_openssl_sign (
	IN int type,
	IN const unsigned char *m,
	IN unsigned int m_len,
	OUT unsigned char *sigret,
	OUT unsigned int *siglen,
	IN OUT const RSA *rsa
) {
#endif
	pkcs11h_certificate_t certificate = _pkcs11h_openssl_get_pkcs11h_certificate (rsa);
	CK_RV rv = CKR_OK;

	int myrsa_size = 0;
	
	unsigned char *enc_alloc = NULL;
	unsigned char *enc = NULL;
	int enc_len = 0;

	PKCS11H_ASSERT (m!=NULL);
	PKCS11H_ASSERT (sigret!=NULL);
	PKCS11H_ASSERT (siglen!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_openssl_sign entered - type=%d, m=%p, m_len=%u, signret=%p, signlen=%p, rsa=%p",
		type,
		m,
		m_len,
		sigret,
		(void *)siglen,
		(void *)rsa
	);

	if (rv == CKR_OK) {
		myrsa_size=RSA_size(rsa);
	}

	if (type == NID_md5_sha1) {
		if (rv == CKR_OK) {
			enc = (unsigned char *)m;
			enc_len = m_len;
		}
	}
	else {
		X509_SIG sig;
		ASN1_TYPE parameter;
		X509_ALGOR algor;
		ASN1_OCTET_STRING digest;

		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_malloc ((void*)&enc, myrsa_size+1)) == CKR_OK
		) {
			enc_alloc = enc;
		}
		
		if (rv == CKR_OK) {
			sig.algor = &algor;
		}

		if (
			rv == CKR_OK &&
			(sig.algor->algorithm = OBJ_nid2obj (type)) == NULL
		) {
			rv = CKR_FUNCTION_FAILED;
		}
	
		if (
			rv == CKR_OK &&
			sig.algor->algorithm->length == 0
		) {
			rv = CKR_KEY_SIZE_RANGE;
		}
	
		if (rv == CKR_OK) {
			parameter.type = V_ASN1_NULL;
			parameter.value.ptr = NULL;
	
			sig.algor->parameter = &parameter;

			sig.digest = &digest;
			sig.digest->data = (unsigned char *)m;
			sig.digest->length = m_len;
		}
	
		if (
			rv == CKR_OK &&
			(enc_len=i2d_X509_SIG (&sig, NULL)) < 0
		) {
			rv = CKR_FUNCTION_FAILED;
		}
	
		if (rv == CKR_OK) {
			unsigned char *p = enc;
			i2d_X509_SIG (&sig, &p);
		}
	}

	if (
		rv == CKR_OK &&
		enc_len > (myrsa_size-RSA_PKCS1_PADDING_SIZE)
	) {
		rv = CKR_KEY_SIZE_RANGE;
	}

	if (rv == CKR_OK) {
		PKCS11H_DEBUG (
			PKCS11H_LOG_DEBUG1,
			"PKCS#11: Performing signature"
		);

		*siglen = myrsa_size;

		if (
			(rv = pkcs11h_certificate_signAny (
				certificate,
				CKM_RSA_PKCS,
				enc,
				enc_len,
				sigret,
				siglen
			)) != CKR_OK
		) {
			PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot perform signature %ld:'%s'", rv, pkcs11h_getMessage (rv));
		}
	}

	if (enc_alloc != NULL) {
		_pkcs11h_free ((void *)&enc_alloc);
	}
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_openssl_sign - return rv=%ld-'%s'",
		rv,
		pkcs11h_getMessage (rv)
	);

	return rv == CKR_OK ? 1 : -1; 
}

static
int
_pkcs11h_openssl_finish (
	IN OUT RSA *rsa
) {
	pkcs11h_openssl_session_t openssl_session = _pkcs11h_openssl_get_openssl_session (rsa);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_openssl_finish - entered rsa=%p",
		(void *)rsa
	);

	RSA_set_app_data (rsa, NULL);
	
	if (openssl_session->orig_finish != NULL) {
		openssl_session->orig_finish (rsa);

#ifdef BROKEN_OPENSSL_ENGINE
		{
			/* We get called TWICE here, once for
			 * releasing the key and also for
			 * releasing the engine.
			 * To prevent endless recursion, FIRST
			 * clear rsa->engine, THEN call engine->finish
			 */
			ENGINE *e = rsa->engine;
			rsa->engine = NULL;
			if (e) {
				ENGINE_finish(e);
			}
		}
#endif
	}

	pkcs11h_openssl_freeSession (openssl_session);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: _pkcs11h_openssl_finish - return"
	);
	
	return 1;
}

pkcs11h_openssl_session_t
pkcs11h_openssl_createSession (
	IN const pkcs11h_certificate_t certificate
) {
	pkcs11h_openssl_session_t openssl_session = NULL;
	PKCS11H_BOOL fOK = TRUE;

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_createSession - entry"
	);

	if (
		fOK &&
		_pkcs11h_malloc (
			(void*)&openssl_session,
			sizeof (struct pkcs11h_openssl_session_s)) != CKR_OK
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot allocate memory");
	}

	if (fOK) {
		const RSA_METHOD *def = RSA_get_default_method();

		memmove (&openssl_session->smart_rsa, def, sizeof(RSA_METHOD));

		openssl_session->orig_finish = def->finish;

		openssl_session->smart_rsa.name = "pkcs11";
		openssl_session->smart_rsa.rsa_priv_dec = _pkcs11h_openssl_dec;
		openssl_session->smart_rsa.rsa_sign = _pkcs11h_openssl_sign;
		openssl_session->smart_rsa.finish = _pkcs11h_openssl_finish;
		openssl_session->smart_rsa.flags  = RSA_METHOD_FLAG_NO_CHECK | RSA_FLAG_EXT_PKEY;
		openssl_session->certificate = certificate;
		openssl_session->nReferenceCount = 1;
	}

	if (!fOK) {
		_pkcs11h_free ((void *)&openssl_session);
	}
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_createSession - return openssl_session=%p",
		(void *)openssl_session
	);

	return openssl_session;
}

void
pkcs11h_openssl_freeSession (
	IN const pkcs11h_openssl_session_t openssl_session
) {
	PKCS11H_ASSERT (openssl_session!=NULL);
	PKCS11H_ASSERT (openssl_session->nReferenceCount>0);
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_freeSession - entry openssl_session=%p, count=%d",
		(void *)openssl_session,
		openssl_session->nReferenceCount
	);

	openssl_session->nReferenceCount--;
	
	if (openssl_session->nReferenceCount == 0) {
		if (openssl_session->x509 != NULL) {
			X509_free (openssl_session->x509);
			openssl_session->x509 = NULL;
		}
		if (openssl_session->certificate != NULL) {
			pkcs11h_freeCertificate (openssl_session->certificate);
			openssl_session->certificate = NULL;
		}
		
		_pkcs11h_free ((void *)&openssl_session);
	}

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_freeSession - return"
	);
}

RSA *
pkcs11h_openssl_getRSA (
	IN const pkcs11h_openssl_session_t openssl_session
) {
	X509 *x509 = NULL;
	RSA *rsa = NULL;
	EVP_PKEY *pubkey = NULL;
	CK_RV rv = CKR_OK;

	pkcs11_openssl_d2i_t d2i1 = NULL;
	PKCS11H_BOOL fOK = TRUE;

	PKCS11H_ASSERT (openssl_session!=NULL);
	PKCS11H_ASSERT (!openssl_session->fInitialized);
	PKCS11H_ASSERT (openssl_session!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_getRSA - entry openssl_session=%p",
		(void *)openssl_session
	);

	if (
		fOK &&
		(x509 = X509_new ()) == NULL
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Unable to allocate certificate object");
	}

	if (
		fOK &&
		(rv = _pkcs11h_ensureCertificateBlob (openssl_session->certificate)) != CKR_OK
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot read X.509 certificate from token %ld-'%s'", rv, pkcs11h_getMessage (rv));
	}

	d2i1 = (pkcs11_openssl_d2i_t)openssl_session->certificate->id->certificate_blob;
	if (
		fOK &&
		!d2i_X509 (&x509, &d2i1, openssl_session->certificate->id->certificate_blob_size)
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Unable to parse X.509 certificate");
	}

	if (
		fOK &&
		(pubkey = X509_get_pubkey (x509)) == NULL
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot get public key");
	}
	
	if (
		fOK &&
		pubkey->type != EVP_PKEY_RSA
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Invalid public key algorithm");
	}

	if (
		fOK &&
		(rsa = EVP_PKEY_get1_RSA (pubkey)) == NULL
	) {
		fOK = FALSE;
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot get RSA key");
	}

	if (fOK) {

		RSA_set_method (rsa, &openssl_session->smart_rsa);
		RSA_set_app_data (rsa, openssl_session);
		openssl_session->nReferenceCount++;
	}
	
#ifdef BROKEN_OPENSSL_ENGINE
	if (fOK) {
		if (!rsa->engine) {
			rsa->engine = ENGINE_get_default_RSA();
		}

		ENGINE_set_RSA(ENGINE_get_default_RSA(), &openssl_session->smart_rsa);
		PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: OpenSSL engine support is broken! Workaround enabled");
	}
#endif
		
	if (fOK) {
		/*
		 * dup x509 so that it won't hold RSA
		 */
		openssl_session->x509 = X509_dup (x509);
		rsa->flags |= RSA_FLAG_SIGN_VER;
		openssl_session->fInitialized = TRUE;
	}
	else {
		if (rsa != NULL) {
			RSA_free (rsa);
			rsa = NULL;
		}
	}

	/*
	 * openssl objects have reference
	 * count, so release them
	 */
	if (pubkey != NULL) {
		EVP_PKEY_free (pubkey);
		pubkey = NULL;
	}

	if (x509 != NULL) {
		X509_free (x509);
		x509 = NULL;
	}
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_getRSA - return rsa=%p",
		(void *)rsa
	);

	return rsa;
}

X509 *
pkcs11h_openssl_getX509 (
	IN const pkcs11h_openssl_session_t openssl_session
) {
	X509 *x509 = NULL;
	
	PKCS11H_ASSERT (openssl_session!=NULL);

	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_getX509 - entry openssl_session=%p",
		(void *)openssl_session
	);

	if (openssl_session->x509 != NULL) {
		x509 = X509_dup (openssl_session->x509);
	}
	
	PKCS11H_DEBUG (
		PKCS11H_LOG_DEBUG2,
		"PKCS#11: pkcs11h_openssl_getX509 - return x509=%p",
		(void *)x509
	);

	return x509;
}

#endif				/* ENABLE_PKCS11H_OPENSSL */

#if defined(ENABLE_PKCS11H_STANDALONE)
/*======================================================================*
 * STANDALONE INTERFACE
 *======================================================================*/

void
pkcs11h_standalone_dump_slots (
	IN const pkcs11h_output_print_t my_output,
	IN const void *pData,
	IN const char * const provider
) {
	CK_RV rv = CKR_OK;

	pkcs11h_provider_t pkcs11h_provider;

	PKCS11H_ASSERT (my_output!=NULL);
	/*PKCS11H_ASSERT (pData) NOT NEEDED */
	PKCS11H_ASSERT (provider!=NULL);

	if (
		rv == CKR_OK &&
		(rv = pkcs11h_initialize ()) != CKR_OK
	) {
		my_output (pData, "PKCS#11: Cannot initialize interface %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
	}

	if (
		rv == CKR_OK &&
		(rv = pkcs11h_addProvider (
			provider,
			provider,
			FALSE,
			(
				PKCS11H_SIGNMODE_MASK_SIGN |
				PKCS11H_SIGNMODE_MASK_RECOVER
			),
			PKCS11H_SLOTEVENT_METHOD_AUTO,
			0,
			FALSE
		)) != CKR_OK
	) {
		my_output (pData, "PKCS#11: Cannot initialize provider %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
	}

	/*
	 * our provider is head
	 */
	if (rv == CKR_OK) {
		pkcs11h_provider = s_pkcs11h_data->providers;
		if (pkcs11h_provider == NULL || !pkcs11h_provider->fEnabled) {
			my_output (pData, "PKCS#11: Cannot get provider %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
			rv = CKR_GENERAL_ERROR;
		}
	}

	if (rv == CKR_OK) {
		CK_INFO info;
		
		if ((rv = pkcs11h_provider->f->C_GetInfo (&info)) != CKR_OK) {
			my_output (pData, "PKCS#11: Cannot get PKCS#11 provider information %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
			rv = CKR_OK;
		}
		else {
			char szManufacturerID[sizeof (info.manufacturerID)+1];
	
			_pkcs11h_fixupFixedString (
				szManufacturerID,
				(char *)info.manufacturerID,
				sizeof (info.manufacturerID)
			);
	
			my_output (
				pData,
				(
					"Provider Information:\n"
					"\tcryptokiVersion:\t%u.%u\n"
					"\tmanufacturerID:\t\t%s\n"
					"\tflags:\t\t\t%d\n"
					"\n"
				),
				info.cryptokiVersion.major,
				info.cryptokiVersion.minor,
				szManufacturerID,
				(unsigned)info.flags
			);
		}
	}
	
	if (rv == CKR_OK) {
		CK_SLOT_ID_PTR slots = NULL;
		CK_ULONG slotnum;
		CK_SLOT_ID slot_index;
		
		if (
			 _pkcs11h_getSlotList (
				pkcs11h_provider,
				CK_FALSE,
				&slots,
				&slotnum
			) != CKR_OK
		) {
			my_output (pData, "PKCS#11: Cannot get slot list %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
		}
		else {
			my_output (
				pData,
				(
					"The following slots are available for use with this provider.\n"
					"Each slot shown below may be used as a parameter to a\n"
					"%s and %s options.\n"
					"\n"
					"Slots: (id - name)\n"
				),
				PKCS11H_PRM_SLOT_TYPE,
				PKCS11H_PRM_SLOT_ID
			);
			for (slot_index=0;slot_index < slotnum;slot_index++) {
				CK_SLOT_INFO info;
	
				if (
					(rv = pkcs11h_provider->f->C_GetSlotInfo (
						slots[slot_index],
						&info
					)) == CKR_OK
				) {
					char szCurrentName[sizeof (info.slotDescription)+1];
				
					_pkcs11h_fixupFixedString (
						szCurrentName,
						(char *)info.slotDescription,
						sizeof (info.slotDescription)
					);
	
					my_output (pData, "\t%lu - %s\n", slots[slot_index], szCurrentName);
				}
			}
		}

		if (slots != NULL) {
			_pkcs11h_free ((void *)&slots);
		}
	}
	
	pkcs11h_terminate ();
}

static
PKCS11H_BOOL
_pkcs11h_standalone_dump_objects_pin_prompt (
	IN const void *pData,
	IN const pkcs11h_token_id_t token,
	OUT char * const szPIN,
	IN const size_t nMaxPIN
) {
	strncpy (szPIN, (char *)pData, nMaxPIN);
	return TRUE;
}

void
_pkcs11h_standalone_dump_objects_hex (
	IN const unsigned char * const p,
	IN const size_t p_size,
	OUT char * const sz,
	IN const size_t max,
	IN const char * const szLinePrefix
) {
	size_t j;

	sz[0] = '\0';

	for (j=0;j<p_size;j+=16) {
		char szLine[3*16+1];
		size_t k;

		szLine[0] = '\0';
		for (k=0;k<16 && j+k<p_size;k++) {
			sprintf (szLine+strlen (szLine), "%02x ", p[j+k]);
		}

		strncat (
			sz,
			szLinePrefix,
			max-1-strlen (sz)
		);
		strncat (
			sz,
			szLine,
			max-1-strlen (sz)
		);
		strncat (
			sz,
			"\n",
			max-1-strlen (sz)
		);
	}

	sz[max-1] = '\0';
}
	
void
pkcs11h_standalone_dump_objects (
	IN const pkcs11h_output_print_t my_output,
	IN const void *pData,
	IN const char * const provider,
	IN const char * const slot,
	IN const char * const pin
) {
	CK_SLOT_ID s;
	CK_RV rv = CKR_OK;

	pkcs11h_provider_t pkcs11h_provider = NULL;
	pkcs11h_token_id_t token_id = NULL;
	pkcs11h_session_t session = NULL;

	PKCS11H_ASSERT (my_output!=NULL);
	/*PKCS11H_ASSERT (pData) NOT NEEDED */
	PKCS11H_ASSERT (provider!=NULL);
	PKCS11H_ASSERT (slot!=NULL);
	PKCS11H_ASSERT (pin!=NULL);

	s = atoi (slot);

	if (
		rv == CKR_OK &&
		(rv = pkcs11h_initialize ()) != CKR_OK
	) {
		my_output (pData, "PKCS#11: Cannot initialize interface %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
	}

	if (
		rv == CKR_OK &&
		(rv = pkcs11h_setPINPromptHook (_pkcs11h_standalone_dump_objects_pin_prompt, (void *)pin)) != CKR_OK
	) {
		my_output (pData, "PKCS#11: Cannot set hooks %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
	}

	if (
		rv == CKR_OK &&
		(rv = pkcs11h_addProvider (
			provider,
			provider,
			FALSE,
			(
				PKCS11H_SIGNMODE_MASK_SIGN |
				PKCS11H_SIGNMODE_MASK_RECOVER
			),
			PKCS11H_SLOTEVENT_METHOD_AUTO,
			0,
			FALSE
		)) != CKR_OK
	) {
		my_output (pData, "PKCS#11: Cannot initialize provider %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
	}

	/*
	 * our provider is head
	 */
	if (rv == CKR_OK) {
		pkcs11h_provider = s_pkcs11h_data->providers;
		if (pkcs11h_provider == NULL || !pkcs11h_provider->fEnabled) {
			my_output (pData, "PKCS#11: Cannot get provider %ld-'%s'\n", rv, pkcs11h_getMessage (rv));
			rv = CKR_GENERAL_ERROR;
		}
	}

	if (rv == CKR_OK) {
		CK_TOKEN_INFO info;
		
		if (
			(rv = pkcs11h_provider->f->C_GetTokenInfo (
				s,
				&info
			)) != CKR_OK
		) {
			my_output (pData, "PKCS#11: Cannot get token information for slot %ld %ld-'%s'\n", s, rv, pkcs11h_getMessage (rv));
			/* Ignore this error */
			rv = CKR_OK;
		}
		else {
			char szLabel[sizeof (info.label)+1];
			char szManufacturerID[sizeof (info.manufacturerID)+1];
			char szModel[sizeof (info.model)+1];
			char szSerialNumber[sizeof (info.serialNumber)+1];
			
			_pkcs11h_fixupFixedString (
				szLabel,
				(char *)info.label,
				sizeof (info.label)
			);
			_pkcs11h_fixupFixedString (
				szManufacturerID,
				(char *)info.manufacturerID,
				sizeof (info.manufacturerID)
			);
			_pkcs11h_fixupFixedString (
				szModel,
				(char *)info.model,
				sizeof (info.model)
			);
			_pkcs11h_fixupFixedString (
				szSerialNumber,
				(char *)info.serialNumber,
				sizeof (info.serialNumber)
			);
	
			my_output (
				pData,
				(
					"Token Information:\n"
					"\tlabel:\t\t%s\n"
					"\tmanufacturerID:\t%s\n"
					"\tmodel:\t\t%s\n"
					"\tserialNumber:\t%s\n"
					"\tflags:\t\t%08x\n"
					"\n"
					"You can access this token using\n"
					"%s \"label\" %s \"%s\" options.\n"
					"\n"
				),
				szLabel,
				szManufacturerID,
				szModel,
				szSerialNumber,
				(unsigned)info.flags,
				PKCS11H_PRM_SLOT_TYPE,
				PKCS11H_PRM_SLOT_ID,
				szLabel
			);

			if (
				rv == CKR_OK &&
				(rv = _pkcs11h_getTokenId (
					&info,
					&token_id
				)) != CKR_OK
			) {
				my_output (pData, "PKCS#11: Cannot get token id for slot %ld %ld-'%s'\n", s, rv, pkcs11h_getMessage (rv));		
				rv = CKR_OK;
			}
		}
	}

	if (token_id != NULL) {
		if (
			(rv = _pkcs11h_getSessionByTokenId (
				token_id,
				&session
			)) != CKR_OK
		) {
			my_output (pData, "PKCS#11: Cannot session for token '%s' %ld-'%s'\n", token_id->label, rv, pkcs11h_getMessage (rv));		
			rv = CKR_OK;
		}
	}

	if (session != NULL) {
		CK_OBJECT_HANDLE *objects = NULL;
		CK_ULONG objects_found = 0;
		CK_ULONG i;

		if (
			(rv = _pkcs11h_login (
				session,
				FALSE,
				TRUE,
				PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT
			)) != CKR_OK
		) {
			my_output (pData, "PKCS#11: Cannot open session to token '%s' %ld-'%s'\n", session->token_id->label, rv, pkcs11h_getMessage (rv));
		}
	
		my_output (
			pData,
			(
				"The following objects are available for use with this token.\n"
				"Each object shown below may be used as a parameter to\n"
				"%s and %s options.\n"
				"\n"
			),
			PKCS11H_PRM_OBJ_TYPE,
			PKCS11H_PRM_OBJ_ID
		);

		if (
			rv == CKR_OK &&
			(rv = _pkcs11h_findObjects (
				session,
				NULL,
				0,
				&objects,
				&objects_found
			)) != CKR_OK
		) {
			my_output (pData, "PKCS#11: Cannot query objects for token '%s' %ld-'%s'\n", session->token_id->label, rv, pkcs11h_getMessage (rv));
		}
	
		for (i=0;rv == CKR_OK && i < objects_found;i++) {
			CK_OBJECT_CLASS attrs_class = 0;
			CK_ATTRIBUTE attrs[] = {
				{CKA_CLASS, &attrs_class, sizeof (attrs_class)}
			};

			if (
				_pkcs11h_getObjectAttributes (
					session,
					objects[i],
					attrs,
					sizeof (attrs) / sizeof (CK_ATTRIBUTE)
				) == CKR_OK
			) {
				if (attrs_class == CKO_CERTIFICATE) {
					CK_ATTRIBUTE attrs_cert[] = {
						{CKA_ID, NULL, 0},
						{CKA_LABEL, NULL, 0},
						{CKA_VALUE, NULL, 0}
					};
					unsigned char *attrs_id = NULL;
					int attrs_id_size = 0;
					unsigned char *attrs_value = NULL;
					int attrs_value_size = 0;
					char *attrs_label = NULL;
					char szHexId[1024];
					char szSubject[1024];
					char szSerial[1024];
					char szNotBefore[1024];

					szSubject[0] = '\0';
					szSerial[0] = '\0';
					szNotBefore[0] = '\0';


					if (
						_pkcs11h_getObjectAttributes (
							session,
							objects[i],
							attrs_cert,
							sizeof (attrs_cert) / sizeof (CK_ATTRIBUTE)
						) == CKR_OK &&
						_pkcs11h_malloc (
							(void *)&attrs_label,
							attrs_cert[1].ulValueLen+1
						) == CKR_OK
					) {
						attrs_id = (unsigned char *)attrs_cert[0].pValue;
						attrs_id_size = attrs_cert[0].ulValueLen;
						attrs_value = (unsigned char *)attrs_cert[2].pValue;
						attrs_value_size = attrs_cert[2].ulValueLen;

						memset (attrs_label, 0, attrs_cert[1].ulValueLen+1);
						memmove (attrs_label, attrs_cert[1].pValue, attrs_cert[1].ulValueLen);
						_pkcs11h_standalone_dump_objects_hex (
							attrs_id,
							attrs_id_size,
							szHexId,
							sizeof (szHexId),
							"\t\t"
						);
					}

					if (attrs_value != NULL) {
						X509 *x509 = NULL;
						BIO *bioSerial = NULL;

						if ((x509 = X509_new ()) == NULL) {
							my_output (pData, "Cannot create x509 context\n");
						}
						else {
							pkcs11_openssl_d2i_t d2i1 = (pkcs11_openssl_d2i_t)attrs_value;
							if (d2i_X509 (&x509, &d2i1, attrs_value_size)) {

								ASN1_TIME *notBefore = X509_get_notBefore (x509);
								if (notBefore != NULL && notBefore->length < (int) sizeof (szNotBefore) - 1) {
									memmove (szNotBefore, notBefore->data, notBefore->length);
									szNotBefore[notBefore->length] = '\0';
								}

								X509_NAME_oneline (
									X509_get_subject_name (x509),
									szSubject,
									sizeof (szSubject)
								);
								szSubject[sizeof (szSubject) - 1] = '\0';
							}
						}

						if ((bioSerial = BIO_new (BIO_s_mem ())) == NULL) {
							my_output (pData, "Cannot create BIO context\n");
						}
						else {
							int n;

							i2a_ASN1_INTEGER(bioSerial, X509_get_serialNumber (x509));
							n = BIO_read (bioSerial, szSerial, sizeof (szSerial)-1);
							if (n<0) {
								szSerial[0] = '\0';
							}
							else {
								szSerial[n] = '\0';
							}
						}

						if (x509 != NULL) {
							X509_free (x509);
							x509 = NULL;
						}
						if (bioSerial != NULL) {
							BIO_free_all (bioSerial);
							bioSerial = NULL;
						}
					}

					my_output (
						pData,
						(
							"Object\n"
							"\tType:\t\t\tCertificate\n"
							"\tCKA_ID:\n"
							"%s"
							"\tCKA_LABEL:\t\t%s\n"
							"\tsubject:\t\t%s\n"
							"\tserialNumber:\t\t%s\n"
							"\tnotBefore:\t\t%s\n"
						),
						szHexId,
						attrs_label,
						szSubject,
						szSerial,
						szNotBefore
					);

					_pkcs11h_free ((void *)&attrs_label);

					_pkcs11h_freeObjectAttributes (
						attrs_cert,
						sizeof (attrs_cert) / sizeof (CK_ATTRIBUTE)
					);
				}
				else if (attrs_class == CKO_PRIVATE_KEY) {
					CK_BBOOL sign_recover = CK_FALSE;
					CK_BBOOL sign = CK_FALSE;
					CK_ATTRIBUTE attrs_key[] = {
						{CKA_SIGN, &sign_recover, sizeof (sign_recover)},
						{CKA_SIGN_RECOVER, &sign, sizeof (sign)}
					};
					CK_ATTRIBUTE attrs_key_common[] = {
						{CKA_ID, NULL, 0},
						{CKA_LABEL, NULL, 0}
					};
					unsigned char *attrs_id = NULL;
					int attrs_id_size = 0;
					char *attrs_label = NULL;
					char szHexId[1024];

					pkcs11h_provider->f->C_GetAttributeValue (
						session->hSession,
						objects[i],
						attrs_key,
						sizeof (attrs_key) / sizeof (CK_ATTRIBUTE)
					);

					if (
						_pkcs11h_getObjectAttributes (
							session,
							objects[i],
							attrs_key_common,
							sizeof (attrs_key_common) / sizeof (CK_ATTRIBUTE)
						) == CKR_OK &&
						_pkcs11h_malloc (
							(void *)&attrs_label,
							attrs_key_common[1].ulValueLen+1
						) == CKR_OK
					) {
						attrs_id = (unsigned char *)attrs_key_common[0].pValue;
						attrs_id_size = attrs_key_common[0].ulValueLen;

						memset (attrs_label, 0, attrs_key_common[1].ulValueLen+1);
						memmove (attrs_label, attrs_key_common[1].pValue, attrs_key_common[1].ulValueLen);

						_pkcs11h_standalone_dump_objects_hex (
							attrs_id,
							attrs_id_size,
							szHexId,
							sizeof (szHexId),
							"\t\t"
						);
							
					}

					my_output (
						pData,
						(
							"Object\n"
							"\tType:\t\t\tPrivate Key\n"
							"\tCKA_ID:\n"
							"%s"
							"\tCKA_LABEL:\t\t%s\n"
							"\tCKA_SIGN:\t\t%s\n"
							"\tCKA_SIGN_RECOVER:\t%s\n"
						),
						szHexId,
						attrs_label,
						sign ? "TRUE" : "FALSE",
						sign_recover ? "TRUE" : "FALSE"
					);

					_pkcs11h_free ((void *)&attrs_label);

					_pkcs11h_freeObjectAttributes (
						attrs_key_common,
						sizeof (attrs_key_common) / sizeof (CK_ATTRIBUTE)
					);
				}
				else if (attrs_class == CKO_PUBLIC_KEY) {
					CK_ATTRIBUTE attrs_key_common[] = {
						{CKA_ID, NULL, 0},
						{CKA_LABEL, NULL, 0}
					};
					unsigned char *attrs_id = NULL;
					int attrs_id_size = 0;
					char *attrs_label = NULL;
					char szHexId[1024];

					if (
						_pkcs11h_getObjectAttributes (
							session,
							objects[i],
							attrs_key_common,
							sizeof (attrs_key_common) / sizeof (CK_ATTRIBUTE)
						) == CKR_OK &&
						_pkcs11h_malloc (
							(void *)&attrs_label,
							attrs_key_common[1].ulValueLen+1
						) == CKR_OK
					) {
						attrs_id = (unsigned char *)attrs_key_common[0].pValue;
						attrs_id_size = attrs_key_common[0].ulValueLen;

						memset (attrs_label, 0, attrs_key_common[1].ulValueLen+1);
						memmove (attrs_label, attrs_key_common[1].pValue, attrs_key_common[1].ulValueLen);

						_pkcs11h_standalone_dump_objects_hex (
							attrs_id,
							attrs_id_size,
							szHexId,
							sizeof (szHexId),
							"\t\t"
						);
							
					}

					my_output (
						pData,
						(
							"Object\n"
							"\tType:\t\t\tPublic Key\n"
							"\tCKA_ID:\n"
							"%s"
							"\tCKA_LABEL:\t\t%s\n"
						),
						szHexId,
						attrs_label
					);

					_pkcs11h_free ((void *)&attrs_label);

					_pkcs11h_freeObjectAttributes (
						attrs_key_common,
						sizeof (attrs_key_common) / sizeof (CK_ATTRIBUTE)
					);
				}
				else if (attrs_class == CKO_DATA) {
					CK_ATTRIBUTE attrs_key_common[] = {
						{CKA_APPLICATION, NULL, 0},
						{CKA_LABEL, NULL, 0}
					};
					char *attrs_application = NULL;
					char *attrs_label = NULL;

					if (
						_pkcs11h_getObjectAttributes (
							session,
							objects[i],
							attrs_key_common,
							sizeof (attrs_key_common) / sizeof (CK_ATTRIBUTE)
						) == CKR_OK &&
						_pkcs11h_malloc (
							(void *)&attrs_application,
							attrs_key_common[0].ulValueLen+1
						) == CKR_OK &&
						_pkcs11h_malloc (
							(void *)&attrs_label,
							attrs_key_common[1].ulValueLen+1
						) == CKR_OK
					) {
						memset (attrs_application, 0, attrs_key_common[0].ulValueLen+1);
						memmove (attrs_application, attrs_key_common[0].pValue, attrs_key_common[0].ulValueLen);
						memset (attrs_label, 0, attrs_key_common[1].ulValueLen+1);
						memmove (attrs_label, attrs_key_common[1].pValue, attrs_key_common[1].ulValueLen);
					}

					my_output (
						pData,
						(
							"Object\n"
							"\tType:\t\t\tData\n"
							"\tCKA_APPLICATION\t\t%s\n"
							"\tCKA_LABEL:\t\t%s\n"
						),
						attrs_application,
						attrs_label
					);

					_pkcs11h_free ((void *)&attrs_application);
					_pkcs11h_free ((void *)&attrs_label);

					_pkcs11h_freeObjectAttributes (
						attrs_key_common,
						sizeof (attrs_key_common) / sizeof (CK_ATTRIBUTE)
					);
				}
				else {
					my_output (
						pData,
						(
							"Object\n"
							"\tType:\t\t\tUnsupported\n"
						)
					);
				}
			}

			_pkcs11h_freeObjectAttributes (
				attrs,
				sizeof (attrs) / sizeof (CK_ATTRIBUTE)
			);

			/*
			 * Ignore any error and
			 * perform next iteration
			 */
			rv = CKR_OK;
		}
	
		if (objects != NULL) {
			_pkcs11h_free ((void *)&objects);
		}

		/*
		 * Ignore this error
		 */
		rv = CKR_OK;
	}

	if (session != NULL) {
		_pkcs11h_releaseSession (session);
		session = NULL;
	}

	if (token_id != NULL) {
		pkcs11h_freeTokenId (token_id);
		token_id = NULL;
	}
	
	pkcs11h_terminate ();
}

#endif				/* ENABLE_PKCS11H_STANDALONE */

#ifdef BROKEN_OPENSSL_ENGINE
static void broken_openssl_init() __attribute__ ((constructor));
static void  broken_openssl_init()
{
	SSL_library_init();
	ENGINE_load_openssl();
	ENGINE_register_all_RSA();
}
#endif

#else
static void dummy (void) {}
#endif				/* PKCS11H_HELPER_ENABLE */