opensc-sys 0.1.1

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

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <limits.h>
#include <time.h>
#ifdef HAVE_GETTIMEOFDAY
#include <sys/time.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <assert.h>
#ifdef ENABLE_OPENSSL
#include <openssl/opensslv.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/pkcs12.h>
#endif

#include "libopensc/sc-ossl-compat.h"
#include "common/compat_strlcpy.h"
#include "common/libscdl.h"
#include "libopensc/pkcs15.h"
#include "libopensc/cardctl.h"
#include "libopensc/asn1.h"
#include "libopensc/log.h"
#include "libopensc/aux-data.h"
#include "profile.h"
#include "pkcs15-init.h"
#include "pkcs11/pkcs11.h"

#define OPENSC_INFO_FILEPATH		"3F0050154946"
#define OPENSC_INFO_FILEID		0x4946
#define OPENSC_INFO_TAG_PROFILE		0x01
#define OPENSC_INFO_TAG_OPTION		0x02

/* Default ID for new key/pin */
#define DEFAULT_ID			0x45
#define DEFAULT_PIN_FLAGS		(SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
#define DEFAULT_PRKEY_FLAGS		(SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
#define DEFAULT_PUBKEY_FLAGS		(SC_PKCS15_CO_FLAG_MODIFIABLE)
#define DEFAULT_SKEY_FLAGS		(SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
#define DEFAULT_CERT_FLAGS		(SC_PKCS15_CO_FLAG_MODIFIABLE)
#define DEFAULT_DATA_FLAGS		(SC_PKCS15_CO_FLAG_MODIFIABLE)

#define TEMPLATE_INSTANTIATE_MIN_INDEX	0x0
#define TEMPLATE_INSTANTIATE_MAX_INDEX	0xFE

/* Maximal number of access conditions that can be defined for one card operation. */
#define SC_MAX_OP_ACS                   16

/* Handle encoding of PKCS15 on the card */
typedef int	(*pkcs15_encoder)(struct sc_context *,
			struct sc_pkcs15_card *, u8 **, size_t *);

static int	sc_pkcs15init_store_data(struct sc_pkcs15_card *,
			struct sc_profile *, struct sc_pkcs15_object *,
			struct sc_pkcs15_der *, struct sc_path *);
static size_t	sc_pkcs15init_keybits(struct sc_pkcs15_bignum *);

static int	sc_pkcs15init_update_dir(struct sc_pkcs15_card *,
			struct sc_profile *profile,
			struct sc_app_info *app);
static int	sc_pkcs15init_update_tokeninfo(struct sc_pkcs15_card *,
			struct sc_profile *profile);
static int	sc_pkcs15init_update_lastupdate(struct sc_pkcs15_card *,
			struct sc_profile *profile);
static int	sc_pkcs15init_update_odf(struct sc_pkcs15_card *,
			struct sc_profile *profile);
static int	sc_pkcs15init_map_usage(unsigned long, int);
static int	do_select_parent(struct sc_profile *, struct sc_pkcs15_card *,
			struct sc_file *, struct sc_file **);
static int	sc_pkcs15init_create_pin(struct sc_pkcs15_card *, struct sc_profile *,
			struct sc_pkcs15_object *, struct sc_pkcs15init_pinargs *);
static int	check_keygen_params_consistency(struct sc_card *card,
			unsigned int alg, struct sc_pkcs15init_prkeyargs *prkey,
			unsigned int *keybits);
static int	check_key_compatibility(struct sc_pkcs15_card *, unsigned int,
			struct sc_pkcs15_prkey *, unsigned int,
			unsigned int, unsigned int);
static int	prkey_fixup(struct sc_pkcs15_card *, struct sc_pkcs15_prkey *);
static int	prkey_bits(struct sc_pkcs15_card *, struct sc_pkcs15_prkey *);
static int	key_pkcs15_algo(struct sc_pkcs15_card *, unsigned int);
static int	select_id(struct sc_pkcs15_card *, int, struct sc_pkcs15_id *);
static int	select_object_path(struct sc_pkcs15_card *, struct sc_profile *,
			struct sc_pkcs15_object *, struct sc_path *);
static int	sc_pkcs15init_get_pin_path(struct sc_pkcs15_card *,
			struct sc_pkcs15_id *, struct sc_path *);
static int	sc_pkcs15init_qualify_pin(struct sc_card *, const char *,
			unsigned int, struct sc_pkcs15_auth_info *);
static struct	sc_pkcs15_df * find_df_by_type(struct sc_pkcs15_card *,
			unsigned int);
static int	sc_pkcs15init_read_info(struct sc_card *card, struct sc_profile *);
static int	sc_pkcs15init_parse_info(struct sc_card *, const unsigned char *, size_t,
			struct sc_profile *);
static int	sc_pkcs15init_write_info(struct sc_pkcs15_card *, struct sc_profile *,
			struct sc_pkcs15_object *);

static struct profile_operations {
	const char *name;
	void *func;
} profile_operations[] = {
	{ "rutoken", (void *) sc_pkcs15init_get_rutoken_ops },
	{ "gpk", (void *) sc_pkcs15init_get_gpk_ops },
	{ "miocos", (void *) sc_pkcs15init_get_miocos_ops },
	{ "flex", (void *) sc_pkcs15init_get_cryptoflex_ops },
	{ "cyberflex", (void *) sc_pkcs15init_get_cyberflex_ops },
	{ "cardos", (void *) sc_pkcs15init_get_cardos_ops },
	{ "etoken", (void *) sc_pkcs15init_get_cardos_ops }, /* legacy */
	{ "jcop", (void *) sc_pkcs15init_get_jcop_ops },
	{ "starcos", (void *) sc_pkcs15init_get_starcos_ops },
	{ "oberthur", (void *) sc_pkcs15init_get_oberthur_ops },
	{ "openpgp", (void *) sc_pkcs15init_get_openpgp_ops },
	{ "setcos", (void *) sc_pkcs15init_get_setcos_ops },
	{ "incrypto34", (void *) sc_pkcs15init_get_incrypto34_ops },
	{ "muscle", (void*) sc_pkcs15init_get_muscle_ops },
	{ "asepcos", (void*) sc_pkcs15init_get_asepcos_ops },
	{ "entersafe",(void*) sc_pkcs15init_get_entersafe_ops },
	{ "epass2003",(void*) sc_pkcs15init_get_epass2003_ops },
	{ "rutoken_ecp", (void *) sc_pkcs15init_get_rtecp_ops },
	{ "rutoken_lite", (void *) sc_pkcs15init_get_rtecp_ops },
	{ "westcos", (void *) sc_pkcs15init_get_westcos_ops },
	{ "myeid", (void *) sc_pkcs15init_get_myeid_ops },
	{ "sc-hsm", (void *) sc_pkcs15init_get_sc_hsm_ops },
	{ "isoApplet", (void *) sc_pkcs15init_get_isoApplet_ops },
	{ "gids", (void *) sc_pkcs15init_get_gids_ops },
#ifdef ENABLE_OPENSSL
	{ "authentic", (void *) sc_pkcs15init_get_authentic_ops },
	{ "iasecc", (void *) sc_pkcs15init_get_iasecc_ops },
#endif
	{ NULL, NULL },
};


static struct sc_pkcs15init_callbacks callbacks = {
	NULL,
	NULL,
};


static void sc_pkcs15init_empty_callback(void *ptr)
{
}

/*
 * Set the application callbacks
 */
void
sc_pkcs15init_set_callbacks(struct sc_pkcs15init_callbacks *cb)
{
	callbacks.get_pin = cb? cb->get_pin : NULL;
	callbacks.get_key = cb? cb->get_key : NULL;
}


/*
 * Returns 1 if the a profile was found in the card's card_driver block
 * in the config file, or 0 otherwise.
 */
static int
get_profile_from_config(struct sc_card *card, char *buffer, size_t size)
{
	struct sc_context *ctx = card->ctx;
	const char *tmp;
	scconf_block **blocks, *blk;
	int i;

	for (i = 0; ctx->conf_blocks[i]; i++) {
		blocks = scconf_find_blocks(ctx->conf, ctx->conf_blocks[i],
					"card_driver",
					card->driver->short_name);
		if (!blocks)
			continue;
		blk = blocks[0];
		free(blocks);
		if (blk == NULL)
			continue;

		tmp = scconf_get_str(blk, "profile", NULL);
		if (tmp != NULL) {
			strlcpy(buffer, tmp, size);
			return 1;
		}
	}

	return 0;
}


static const char *
find_library(struct sc_context *ctx, const char *name)
{
	int          i;
	const char   *libname = NULL;
	scconf_block *blk, **blocks;

	for (i = 0; ctx->conf_blocks[i]; i++) {
		blocks = scconf_find_blocks(ctx->conf, ctx->conf_blocks[i], "framework", "pkcs15");
		if (!blocks)
			continue;
		blk = blocks[0];
		free(blocks);
		if (blk == NULL)
			continue;
		blocks = scconf_find_blocks(ctx->conf, blk, "pkcs15init", name);
		if (!blocks)
			continue;
		blk = blocks[0];
		free(blocks);
		if (blk == NULL)
			continue;
		libname = scconf_get_str(blk, "module", NULL);
		break;
	}
	if (!libname) {
		sc_log(ctx, "unable to locate pkcs15init driver for '%s'", name);
	}
	return libname;
}


static void *
load_dynamic_driver(struct sc_context *ctx, void **dll,
	const char *name)
{
	const char *version, *libname;
	void *handle;
	void *(*modinit)(const char *)  = NULL;
	const char *(*modversion)(void) = NULL;

	libname = find_library(ctx, name);
	if (!libname)
		return NULL;
	handle = sc_dlopen(libname);
	if (handle == NULL) {
		sc_log(ctx, "Module %s: cannot load '%s' library: %s", name, libname, sc_dlerror());
		return NULL;
	}

	/* verify correctness of module */
	modinit    = (void *(*)(const char *)) sc_dlsym(handle, "sc_module_init");
	modversion = (const char *(*)(void)) sc_dlsym(handle, "sc_driver_version");
	if (modinit == NULL || modversion == NULL) {
		sc_log(ctx, "dynamic library '%s' is not a OpenSC module",libname);
		sc_dlclose(handle);
		return NULL;
	}
	/* verify module version */
	version = modversion();
	if (version == NULL || strncmp(version, "0.9.", strlen("0.9.")) > 0) {
		sc_log(ctx,"dynamic library '%s': invalid module version",libname);
		sc_dlclose(handle);
		return NULL;
	}
	*dll = handle;
	sc_log(ctx, "successfully loaded pkcs15init driver '%s'", name);

	return modinit(name);
}


/*
 * Set up profile
 */
int
sc_pkcs15init_bind(struct sc_card *card, const char *name, const char *profile_option,
		struct sc_app_info *app_info, struct sc_profile **result)
{
	struct sc_context *ctx = card->ctx;
	struct sc_profile *profile;
	struct sc_pkcs15init_operations * (* func)(void) = NULL;
	const char	*driver = card->driver->short_name;
	char		card_profile[PATH_MAX];
	int		r, i;

	LOG_FUNC_CALLED(ctx);
	/* Put the card into administrative mode */
	r = sc_pkcs15init_set_lifecycle(card, SC_CARDCTRL_LIFECYCLE_ADMIN);
	if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
		LOG_TEST_RET(ctx, r, "Set lifecycle error");

	profile = sc_profile_new();
	profile->card = card;

	for (i = 0; profile_operations[i].name; i++) {
		if (!strcasecmp(driver, profile_operations[i].name)) {
			func = (struct sc_pkcs15init_operations *(*)(void)) profile_operations[i].func;
			break;
		}
	}
	if (!func) {
		/* no builtin support for this driver => look if there's a
		 * dynamic module for this card */
		func = (struct sc_pkcs15init_operations *(*)(void)) load_dynamic_driver(card->ctx, &profile->dll, driver);
	}
	if (func) {
		profile->ops = func();
	}
	else {
		sc_log(ctx, "Unsupported card driver %s", driver);
		sc_profile_free(profile);
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card driver");
	}

	/* Massage the main profile name to see if there are
	 * any options in there
	 */
	profile->name = strdup(name);
	if (strchr(profile->name, '+') != NULL) {
		char	*s;

		i = 0;
		(void) strtok(profile->name, "+");
		while ((s = strtok(NULL, "+")) != NULL) {
			if (i < SC_PKCS15INIT_MAX_OPTIONS-1)
				profile->options[i++] = strdup(s);
		}
	}

	r = sc_pkcs15init_read_info(card, profile);
	if (r < 0) {
		sc_profile_free(profile);
		LOG_TEST_RET(ctx, r, "Read info error");
	}

	/* Check the config file for a profile name.
	 * If none is defined, use the default profile name.
	 */
	if (!get_profile_from_config(card, card_profile, sizeof(card_profile)))
		strlcpy(card_profile, driver, sizeof card_profile);
	if (profile_option != NULL)
		strlcpy(card_profile, profile_option, sizeof(card_profile));

	do   {
		r = sc_profile_load(profile, profile->name);
		if (r < 0)   {
			sc_log(ctx, "Failed to load profile '%s': %s", profile->name, sc_strerror(r));
			break;
		}

		r = sc_profile_load(profile, card_profile);
		if (r < 0)   {
			sc_log(ctx, "Failed to load profile '%s': %s", card_profile, sc_strerror(r));
			break;
		}

		r = sc_profile_finish(profile, app_info);
		if (r < 0)
			sc_log(ctx, "Failed to finalize profile: %s", sc_strerror(r));
	}  while (0);

	if (r < 0)   {
		sc_profile_free(profile);
		LOG_TEST_RET(ctx, r, "Load profile error");
	}

	if (app_info && app_info->aid.len)   {
		struct sc_path path;

		if (card->ef_atr && card->ef_atr->aid.len)   {
			sc_log(ctx, "sc_pkcs15init_bind() select MF using EF.ATR data");
			memset(&path, 0, sizeof(struct sc_path));
			path.type = SC_PATH_TYPE_DF_NAME;
			path.aid = card->ef_atr->aid;
			r = sc_select_file(card, &path, NULL);
			if (r)
				return r;
		}

		if (app_info->path.len)   {
			path = app_info->path;
		}
		else   {
			memset(&path, 0, sizeof(struct sc_path));
			path.type = SC_PATH_TYPE_DF_NAME;
			path.aid = app_info->aid;
		}
		sc_log(ctx, "sc_pkcs15init_bind() select application path(type:%X) '%s'", path.type, sc_print_path(&path));
		r = sc_select_file(card, &path, NULL);
	}

	*result = profile;
	LOG_FUNC_RETURN(ctx, r);
}


void
sc_pkcs15init_unbind(struct sc_profile *profile)
{
	int r;
	struct sc_context *ctx = profile->card->ctx;

	LOG_FUNC_CALLED(ctx);
	sc_log(ctx, "Pksc15init Unbind: %i:%p:%i", profile->dirty, profile->p15_data, profile->pkcs15.do_last_update);
	if (profile->dirty != 0 && profile->p15_data != NULL && profile->pkcs15.do_last_update) {
		r = sc_pkcs15init_update_lastupdate(profile->p15_data, profile);
		if (r < 0)
			sc_log(ctx, "Failed to update TokenInfo: %s", sc_strerror(r));
	}
	if (profile->dll)
		sc_dlclose(profile->dll);
	sc_profile_free(profile);
}


void
sc_pkcs15init_set_p15card(struct sc_profile *profile, struct sc_pkcs15_card *p15card)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *p15objects[10];
	int i, r, nn_objs;

	LOG_FUNC_CALLED(ctx);

	/* Prepare pin-domain instantiation:
	 * for every present local User PIN, add to the profile EF list the named PIN path. */
	nn_objs = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, p15objects, 10);
	for (i = 0; i < nn_objs; i++) {
		struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) p15objects[i]->data;
		struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
		struct sc_file *file = NULL;

		if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
			continue;
		if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
			continue;
		if (!auth_info->path.len)
			continue;

		r = sc_profile_get_file_by_path(profile, &auth_info->path, &file);
                if (r == SC_ERROR_FILE_NOT_FOUND)   {
			if (!sc_select_file(p15card->card, &auth_info->path, &file))   {
				char pin_name[16];

				sprintf(pin_name, "pin-dir-%02X%02X", file->path.value[file->path.len - 2],
						file->path.value[file->path.len - 1]);
				sc_log(ctx, "add '%s' to profile file list", pin_name);
				sc_profile_add_file(profile, pin_name, file);
			}
		}

		sc_file_free(file);
	}

	profile->p15_data = p15card;
	sc_log(ctx, "sc_pkcs15init_set_p15card() returns");
}


/*
 * Set the card's lifecycle
 */
int
sc_pkcs15init_set_lifecycle(struct sc_card *card, int lcycle)
{
	return sc_card_ctl(card, SC_CARDCTL_LIFECYCLE_SET, &lcycle);
}


/*
 * Erase the card
 */
int
sc_pkcs15init_erase_card(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_aid *aid)
{
	struct sc_context *ctx = NULL;
	int rv;

	if (!p15card)
		return SC_ERROR_INVALID_ARGUMENTS;

	ctx = p15card->card->ctx;
	LOG_FUNC_CALLED(ctx);
	/* Needs the 'SOPIN' AUTH pkcs15 object.
	 * So that, SOPIN can be found by it's reference. */
	if (sc_pkcs15_bind(p15card->card, aid, &p15card) >= 0)
		profile->p15_data = p15card;

	if (profile->ops->erase_card == NULL)
		LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);

	rv = profile->ops->erase_card(profile, p15card);

	LOG_FUNC_RETURN(ctx, rv);
}


int
sc_pkcs15init_erase_card_recursively(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile)
{
	struct sc_file	*df = profile->df_info->file, *dir;
	int		r;

	/* Delete EF(DIR). This may not be very nice
	 * against other applications that use this file, but
	 * extremely useful for testing :)
	 * Note we need to delete it before the DF because we create
	 * it *after* the DF. Some cards (e.g. the cryptoflex) want
	 * us to delete files in reverse order of creation.
	 * */
	if (sc_profile_get_file(profile, "DIR", &dir) >= 0) {
		r = sc_pkcs15init_rmdir(p15card, profile, dir);
		sc_file_free(dir);
		if (r < 0 && r != SC_ERROR_FILE_NOT_FOUND)   {
			sc_free_apps(p15card->card);
			return r;
		}
	}

	r = sc_select_file(p15card->card, &df->path, &df);
	if (r >= 0) {
		r = sc_pkcs15init_rmdir(p15card, profile, df);
		sc_file_free(df);
	}
	if (r == SC_ERROR_FILE_NOT_FOUND)
		r = 0;

	sc_free_apps(p15card->card);
	return r;
}


int
sc_pkcs15init_delete_by_path(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
		const struct sc_path *file_path)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file *parent = NULL, *file = NULL;
	struct sc_path path;
	int rv;
	/*int file_type = SC_FILE_TYPE_DF;*/

	LOG_FUNC_CALLED(ctx);
	sc_log(ctx, "trying to delete '%s'", sc_print_path(file_path));

	/* For some cards, to delete file should be satisfied the 'DELETE' ACL of the file itself,
	 * for the others the 'DELETE' ACL of parent.
	 * Let's start from the file's 'DELETE' ACL.
	 *
	 * TODO: 'DELETE_SELF' exists. Proper solution would be to use this acl by every
	 * card (driver and profile) that uses self delete ACL.
	 */
	/* Select the file itself */
        path = *file_path;
        rv = sc_select_file(p15card->card, &path, &file);
        LOG_TEST_RET(ctx, rv, "cannot select file to delete");

	if (sc_file_get_acl_entry(file, SC_AC_OP_DELETE_SELF))   {
		sc_log(ctx, "Found 'DELETE-SELF' acl");
		rv = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_DELETE_SELF);
		sc_file_free(file);
	}
	else if (sc_file_get_acl_entry(file, SC_AC_OP_DELETE))   {
		sc_log(ctx, "Found 'DELETE' acl");
	        rv = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_DELETE);
		sc_file_free(file);
	}
	else    {
		sc_log(ctx, "Try to get the parent's 'DELETE' access");
		/*file_type = file->type;*/
		if (file_path->len >= 2) {
			/* Select the parent DF */
			path.len -= 2;
			rv = sc_select_file(p15card->card, &path, &parent);
			LOG_TEST_RET(ctx, rv, "Cannot select parent");

			rv = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_DELETE);
			sc_file_free(parent);
			LOG_TEST_RET(ctx, rv, "parent 'DELETE' authentication failed");
		}
	}
	LOG_TEST_RET(ctx, rv, "'DELETE' authentication failed");

	/* Reselect file to delete: current path could be changed by 'verify PIN' procedure */
	path = *file_path;
	rv = sc_select_file(p15card->card, &path, &file);
	LOG_TEST_RET(ctx, rv, "cannot select file to delete");

	memset(&path, 0, sizeof(path));
	path.type = SC_PATH_TYPE_FILE_ID;
	path.value[0] = file_path->value[file_path->len - 2];
	path.value[1] = file_path->value[file_path->len - 1];
	path.len = 2;

	/* Reselect file to delete if the parent DF was selected and it's not DF. */
/*
	if (file_type != SC_FILE_TYPE_DF)   {
		rv = sc_select_file(p15card->card, &path, &file);
		LOG_TEST_RET(ctx, rv, "cannot select file to delete");
	}
*/

	sc_log(ctx, "Now really delete file");
	rv = sc_delete_file(p15card->card, &path);
	LOG_FUNC_RETURN(ctx, rv);
}


/*
 * Try to delete a file (and, in the DF case, its contents).
 * Note that this will not work if a pkcs#15 file's ERASE AC
 * references a pin other than the SO pin.
 */
int
sc_pkcs15init_rmdir(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_file *df)
{
	struct sc_context *ctx = p15card->card->ctx;
	unsigned char buffer[1024];
	struct sc_path	path;
	struct sc_file	*file, *parent;
	int		r = 0, nfids;

	if (df == NULL)
		return SC_ERROR_INTERNAL;
	sc_log(ctx, "sc_pkcs15init_rmdir(%s)", sc_print_path(&df->path));

	if (df->type == SC_FILE_TYPE_DF) {
		r = sc_pkcs15init_authenticate(profile, p15card, df, SC_AC_OP_LIST_FILES);
		if (r < 0)
			return r;
		r = sc_list_files(p15card->card, buffer, sizeof(buffer));
		if (r < 0)
			return r;

		path = df->path;
		path.len += 2;

		nfids = r / 2;
		while (r >= 0 && nfids--) {
			path.value[path.len-2] = buffer[2*nfids];
			path.value[path.len-1] = buffer[2*nfids+1];
			r = sc_select_file(p15card->card, &path, &file);
			if (r < 0) {
				if (r == SC_ERROR_FILE_NOT_FOUND)
					continue;
				break;
			}
			r = sc_pkcs15init_rmdir(p15card, profile, file);
			sc_file_free(file);
		}

		if (r < 0)
			return r;
	}

	/* Select the parent DF */
	path = df->path;
	path.len -= 2;
	r = sc_select_file(p15card->card, &path, &parent);
	if (r < 0)
		return r;

	r = sc_pkcs15init_authenticate(profile, p15card, df, SC_AC_OP_DELETE);
	if (r < 0) {
		sc_file_free(parent);
		return r;
	}
	r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_DELETE);
	sc_file_free(parent);
	if (r < 0)
		return r;

	memset(&path, 0, sizeof(path));
	path.type = SC_PATH_TYPE_FILE_ID;
	path.value[0] = df->id >> 8;
	path.value[1] = df->id & 0xFF;
	path.len = 2;

	/* ensure that the card is in the correct lifecycle */
	r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
	if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
		return r;

	r = sc_delete_file(p15card->card, &path);
	return r;
}


int
sc_pkcs15init_finalize_card(struct sc_card *card, struct sc_profile *profile)
{
	if (profile->ops->finalize_card == NULL)
		return SC_ERROR_NOT_SUPPORTED;
	return profile->ops->finalize_card(card);
}


int
sc_pkcs15init_finalize_profile(struct sc_card *card, struct sc_profile *profile,
		struct sc_aid *aid)
{
	struct sc_context *ctx = card->ctx;
	const struct sc_app_info *app = NULL;
	int rv;

	LOG_FUNC_CALLED(ctx);
	if (card->app_count < 0 && SC_SUCCESS != sc_enum_apps(card))
		sc_log(ctx, "Could not enumerate apps");

	if (aid)   {
		sc_log(ctx, "finalize profile for AID %s", sc_dump_hex(aid->value, aid->len));
		app = sc_find_app(card, aid);
	}
	else if (card->app_count == 1) {
		app = card->app[0];
	}
	else if (card->app_count > 1) {
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Need AID defined in this context");
	}

	sc_log(ctx, "Finalize profile with application '%s'", app ? app->label : "default");
	rv = sc_profile_finish(profile, app);

	sc_log(ctx, "sc_pkcs15init_finalize_profile() returns %i", rv);
	LOG_FUNC_RETURN(ctx, rv);
}

/*
 * Initialize the PKCS#15 application
 */
int
sc_pkcs15init_add_app(struct sc_card *card, struct sc_profile *profile,
		struct sc_pkcs15init_initargs *args)
{
	struct sc_context *ctx = card->ctx;
	struct sc_pkcs15_card	*p15card = profile->p15_spec;
	struct sc_pkcs15_auth_info pin_ainfo, puk_ainfo;
	struct sc_pkcs15_pin_attributes *pin_attrs = &pin_ainfo.attrs.pin;
	struct sc_pkcs15_object	*pin_obj = NULL;
	struct sc_app_info	*app;
	struct sc_file		*df = profile->df_info->file;
	int			r = SC_SUCCESS;
	int			has_so_pin = args->so_pin_len != 0;

	LOG_FUNC_CALLED(ctx);
	p15card->card = card;

	/* FIXME:
	 * Some cards need pincache
	 *  for ex. to create temporary CHV key with the value of default AUTH key.
	 */
	p15card->opts.use_pin_cache = 1;

	if (card->app_count >= SC_MAX_CARD_APPS)
		LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Too many applications on this card.");

	/* In case of pinpad readers check if SO PIN is defined in a profile */
	if (!has_so_pin && (card->reader->capabilities & SC_READER_CAP_PIN_PAD)) {
		sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &pin_ainfo);
		/* If found, assume we want SO PIN */
		has_so_pin = pin_ainfo.attrs.pin.reference != -1;
	}

	/* If the profile requires an SO PIN, check min/max length */
	if (has_so_pin) {
		const char	*pin_label;

		if (args->so_pin_len) {
			sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &pin_ainfo);
			r = sc_pkcs15init_qualify_pin(card, "SO PIN", args->so_pin_len, &pin_ainfo);
			LOG_TEST_RET(ctx, r, "Failed to qualify SO PIN");
		}

		/* Path encoded only for local SO PIN */
		if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_LOCAL)
			pin_ainfo.path = df->path;

		/* Select the PIN reference */
		if (profile->ops->select_pin_reference) {
			r = profile->ops->select_pin_reference(profile, p15card, &pin_ainfo);
			LOG_TEST_RET(ctx, r, "Failed to select card specific PIN reference");
		}

		sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PUK, &puk_ainfo);
		r = sc_pkcs15init_qualify_pin(card, "SO PUK", args->so_puk_len, &puk_ainfo);
		LOG_TEST_RET(ctx, r, "Failed to qualify SO PUK");

		if (!(pin_label = args->so_pin_label)) {
			if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
				pin_label = "Security Officer PIN";
			else
				pin_label = "User PIN";
		}

		if (args->so_puk_len == 0)
			pin_attrs->flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;

		pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, pin_label, NULL, &pin_ainfo);
		if (pin_obj)   {
			/* When composing ACLs to create 'DIR' DF,
			 *	the references of the not-yet-existing PINs can be requested.
			 * For this, create a 'virtual' AUTH object 'SO PIN', accessible by the card specific part,
			 * but not yet written into the on-card PKCS#15.
			 */
			sc_log(ctx, "Add virtual SO_PIN('%.*s',flags:%X,reference:%i,path:'%s')", (int) sizeof pin_obj->label, pin_obj->label,
					pin_attrs->flags, pin_attrs->reference, sc_print_path(&pin_ainfo.path));

			r = sc_pkcs15_add_object(p15card, pin_obj);
			LOG_TEST_RET(ctx, r, "Failed to add 'SOPIN' AUTH object");
		}
	}

	/* Perform card-specific initialization */

	if (profile->ops->init_card)   {
		r = profile->ops->init_card(profile, p15card);
		if (r < 0 && pin_obj)   {
			sc_pkcs15_remove_object(p15card, pin_obj);
			sc_pkcs15_free_object(pin_obj);
		}
		LOG_TEST_RET(ctx, r, "Card specific init failed");
	}

	/* Create the application directory */
	if (profile->ops->create_dir)
		r = profile->ops->create_dir(profile, p15card, df);
	LOG_TEST_RET(ctx, r, "Create 'DIR' error");

	/* Store SO PIN */
	if (pin_obj && profile->ops->create_pin)
		r = profile->ops->create_pin(profile, p15card, df, pin_obj,
				args->so_pin, args->so_pin_len,
				args->so_puk, args->so_puk_len);

	if (pin_obj)
		/* Remove 'virtual' AUTH object . */
		sc_pkcs15_remove_object(p15card, pin_obj);

	if (r < 0)
		sc_pkcs15_free_object(pin_obj);
	LOG_TEST_RET(ctx, r, "Card specific create application DF failed");

	/* Store the PKCS15 information on the card */
	app = (struct sc_app_info *)calloc(1, sizeof(*app));
	if (app == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Failed to allocate application info");

	app->path = p15card->file_app->path;
	if (p15card->file_app->namelen <= SC_MAX_AID_SIZE) {
		app->aid.len = p15card->file_app->namelen;
		memcpy(app->aid.value, p15card->file_app->name, app->aid.len);
	}

	/* set serial number if explicitly specified */
	if (args->serial)   {
		sc_pkcs15init_set_serial(profile, args->serial);
	}
	else {
		/* otherwise try to get the serial number from the card */
		struct sc_serial_number serialnr;

		r = sc_card_ctl(card, SC_CARDCTL_GET_SERIALNR, &serialnr);
		if (r == SC_SUCCESS) {
			char hex_serial[SC_MAX_SERIALNR * 2 + 1];

			sc_bin_to_hex(serialnr.value, serialnr.len, hex_serial, sizeof(hex_serial), 0);
			sc_pkcs15init_set_serial(profile, hex_serial);
		}
	}

	if (args->label) {
		if (p15card->tokeninfo->label)
			free(p15card->tokeninfo->label);
		p15card->tokeninfo->label = strdup(args->label);
	}
	app->label = strdup(p15card->tokeninfo->label);

	/* See if we've set an SO PIN */
	r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
	if (r >= 0) {
		r = sc_pkcs15init_update_dir(p15card, profile, app);
		if (r >= 0) {
			r = sc_pkcs15init_update_tokeninfo(p15card, profile);
		} else {
			/* FIXME: what to do if sc_pkcs15init_update_dir failed? */
			free(app->label);
			free(app); /* unused */
		}
	}
	else {
		free(app->label);
		free(app); /* unused */
	}

	sc_pkcs15init_write_info(p15card, profile, pin_obj);
	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Store a PIN/PUK pair
 */
static int
sc_pkcs15init_store_puk(struct sc_pkcs15_card *p15card,
			struct sc_profile *profile,
			struct sc_pkcs15init_pinargs *args)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object	*pin_obj;
	struct sc_pkcs15_auth_info *auth_info;
	int			r;
	char puk_label[0x30];

	LOG_FUNC_CALLED(ctx);
	if (!args->puk_id.len)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "PUK auth ID not supplied");

	/* Make sure we don't get duplicate PIN IDs */
	r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->puk_id, NULL);
	if (r != SC_ERROR_OBJECT_NOT_FOUND)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "There already is a PIN with this ID.");

	if (!args->puk_label)   {
		if (args->label)
			snprintf(puk_label, sizeof(puk_label), "%s (PUK)", args->label);
		else
			snprintf(puk_label, sizeof(puk_label), "User PUK");

		args->puk_label = puk_label;
	}

	args->pin = args->puk;
	args->pin_len = args->puk_len;
	args->puk = NULL;
	args->puk_len = 0;

	pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, args->puk_label, NULL, NULL);
	if (pin_obj == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate PIN object");

	auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;

	sc_profile_get_pin_info(profile, SC_PKCS15INIT_USER_PUK, auth_info);
	auth_info->auth_id = args->puk_id;

	/* Now store the PINs */
	if (profile->ops->create_pin)
		r = sc_pkcs15init_create_pin(p15card, profile, pin_obj, args);
	else {
		sc_pkcs15_free_object(pin_obj);
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "In Old API store PUK object is not supported");
	}

	if (r >= 0)
		r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
	else
		sc_pkcs15_free_object(pin_obj);

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


int
sc_pkcs15init_store_pin(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
			struct sc_pkcs15init_pinargs *args)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object	*pin_obj;
	struct sc_pkcs15_auth_info *auth_info;
	int			r;

	LOG_FUNC_CALLED(ctx);
	/* No auth_id given: select one */
	if (args->auth_id.len == 0) {
		unsigned int	n;

		args->auth_id.len = 1;
		for (n = 1, r = 0; n < 256; n++) {
			args->auth_id.value[0] = n;
			r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->auth_id, NULL);
			if (r == SC_ERROR_OBJECT_NOT_FOUND)
				break;
		}

		if (r != SC_ERROR_OBJECT_NOT_FOUND)
			LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "No auth_id specified for new PIN");
	}
	else   {
		/* Make sure we don't get duplicate PIN IDs */
		r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->auth_id, NULL);
		if (r != SC_ERROR_OBJECT_NOT_FOUND)
			LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "There already is a PIN with this ID.");
	}

	pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, args->label, NULL, NULL);
	if (pin_obj == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate PIN object");

	auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;

	sc_profile_get_pin_info(profile, SC_PKCS15INIT_USER_PIN, auth_info);
	auth_info->auth_id = args->auth_id;

	/* Now store the PINs */
	sc_log(ctx, "Store PIN(%.*s,authID:%s)", (int) sizeof pin_obj->label, pin_obj->label, sc_pkcs15_print_id(&auth_info->auth_id));
	r = sc_pkcs15init_create_pin(p15card, profile, pin_obj, args);
	if (r < 0)
		sc_pkcs15_free_object(pin_obj);
	LOG_TEST_RET(ctx, r, "Card specific create PIN failed.");

	r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
	if (r < 0)
		sc_pkcs15_free_object(pin_obj);
	LOG_TEST_RET(ctx, r, "Failed to add PIN object");

	if (args->puk_id.len)
		r = sc_pkcs15init_store_puk(p15card, profile, args);

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


static int
sc_pkcs15init_create_pin(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile,
		struct sc_pkcs15_object *pin_obj,
		struct sc_pkcs15init_pinargs *args)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;
	struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
	struct sc_file	*df = profile->df_info->file;
	int		r, retry = 0;

	LOG_FUNC_CALLED(ctx);
	/* Some cards need to keep all their PINs in separate directories.
	 * Create a subdirectory now, and put the pin into
	 * this subdirectory
	 */
	if (profile->pin_domains) {
		if (!profile->ops->create_domain)
			LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN domains not supported.");

		r = profile->ops->create_domain(profile, p15card, &auth_info->auth_id, &df);
		LOG_TEST_RET(ctx, r, "Card specific create domain failed");
	}

	/* Path encoded only for local PINs */
	if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_LOCAL)
		auth_info->path = df->path;

	/* pin_info->reference = 0; */

	/* Loop until we come up with an acceptable pin reference */
	while (1) {
		if (profile->ops->select_pin_reference) {
			r = profile->ops->select_pin_reference(profile, p15card, auth_info);
			LOG_TEST_RET(ctx, r, "Card specific select PIN reference failed");

			retry = 1;
		}

		r = sc_pkcs15_find_pin_by_reference(p15card, &auth_info->path, pin_attrs->reference, NULL);
		if (r == SC_ERROR_OBJECT_NOT_FOUND)
			break;

		if (r != 0 || !retry)
			/* Other error trying to retrieve pin obj */
			LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Failed to allocate PIN reference.");

		pin_attrs->reference++;
	}

	if (args->puk_len == 0)
		pin_attrs->flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;

	sc_log(ctx, "create PIN with reference:%X, flags:%X, path:%s",
			pin_attrs->reference, pin_attrs->flags, sc_print_path(&auth_info->path));
	r = profile->ops->create_pin(profile, p15card,
			df, pin_obj,
			args->pin, args->pin_len,
			args->puk, args->puk_len);

	if (df != profile->df_info->file)
		sc_file_free(df);

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Default function for creating a pin subdirectory
 */
int
sc_pkcs15_create_pin_domain(struct sc_profile *profile,
		struct sc_pkcs15_card *p15card, const struct sc_pkcs15_id *id,
		struct sc_file **ret)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file *df = profile->df_info->file;
	int	r;

	sc_log(ctx, "create PIN domain (path:%s,ID:%s)", sc_print_path(&df->path), sc_pkcs15_print_id(id));
	/* Instantiate PIN directory just below the application DF */
	r = sc_profile_instantiate_template(profile, "pin-domain", &df->path, "pin-dir", id, ret);
	if (r >= 0)   {
		sc_log(ctx, "create PIN DF(path:%s)", sc_print_path(&(*ret)->path));
		r = profile->ops->create_dir(profile, p15card, *ret);
	}

	return r;
}

static int
sc_pkcs15init_encode_prvkey_content(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *prvkey,
		struct sc_pkcs15_object *object)
{
	struct sc_context *ctx = p15card->card->ctx;

	LOG_FUNC_CALLED(ctx);
	if (prvkey->algorithm == SC_ALGORITHM_RSA)   {
		struct sc_pkcs15_pubkey pubkey;
		int rv;

		pubkey.algorithm = prvkey->algorithm;
		pubkey.u.rsa.modulus = prvkey->u.rsa.modulus;
		pubkey.u.rsa.exponent = prvkey->u.rsa.exponent;

		rv = sc_pkcs15_encode_pubkey(ctx, &pubkey, &object->content.value, &object->content.len);
		LOG_TEST_RET(ctx, rv, "Failed to encode public key");
	}
	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}

/*
 * Prepare private key download, and initialize a prkdf entry
 */
static int
sc_pkcs15init_init_prkdf(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_prkeyargs *keyargs, struct sc_pkcs15_prkey *key, int keybits,
		struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_prkey_info *key_info;
	struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
	struct sc_pkcs15_object *object = NULL;
	const char	*label;
	unsigned int	usage;
	int		r = 0, key_type;

	LOG_FUNC_CALLED(ctx);
	if (!res_obj || !keybits) {
		r = SC_ERROR_INVALID_ARGUMENTS;
		LOG_TEST_GOTO_ERR(ctx, r, "Initialize PrKDF entry failed");
	}

	*res_obj = NULL;

	if ((usage = keyargs->usage) == 0) {
		usage = SC_PKCS15_PRKEY_USAGE_SIGN;
		if (keyargs->x509_usage)
			usage = sc_pkcs15init_map_usage(keyargs->x509_usage, 1);
	}

	if ((label = keyargs->label) == NULL)
		label = DEFAULT_PRIVATE_KEY_LABEL;

	/* Create the prkey object now.
	 * If we find out below that we're better off reusing an
	 * existing object, we'll ditch this one */
	key_type = key_pkcs15_algo(p15card, key->algorithm);
	r = key_type;
	LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key type");

	object = sc_pkcs15init_new_object(key_type, label, &keyargs->auth_id, NULL);
	if (object == NULL)
		LOG_TEST_GOTO_ERR(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate new PrKey object");

	key_info = (struct sc_pkcs15_prkey_info *) object->data;
	key_info->usage = usage;
	key_info->native = 1;
	key_info->key_reference = 0;
	key_info->modulus_length = keybits;
	key_info->access_flags = keyargs->access_flags;
	object->user_consent = keyargs->user_consent;
	/* Path is selected below */

	if (keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE) {
		key_info->access_flags &= ~SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE;
	}

	/* Select a Key ID if the user didn't specify one,
	 * otherwise make sure it's compatible with our intended use */
	r = select_id(p15card, SC_PKCS15_TYPE_PRKEY, &keyargs->id);
	LOG_TEST_GOTO_ERR(ctx, r, "Cannot select ID for PrKey object");

	key_info->id = keyargs->id;

	if (key->algorithm == SC_ALGORITHM_GOSTR3410) {
		key_info->params.len = sizeof(*keyinfo_gostparams);
		/* FIXME: malloc() call in pkcs15init, but free() call
		 * in libopensc (sc_pkcs15_free_prkey_info) */
		key_info->params.data = malloc(key_info->params.len);
		if (!key_info->params.data) {
			r = SC_ERROR_OUT_OF_MEMORY;
			LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate memory for GOST parameters");
		}
		keyinfo_gostparams = key_info->params.data;
		keyinfo_gostparams->gostr3410 = keyargs->params.gost.gostr3410;
		keyinfo_gostparams->gostr3411 = keyargs->params.gost.gostr3411;
		keyinfo_gostparams->gost28147 = keyargs->params.gost.gost28147;
	}
	else if (key->algorithm == SC_ALGORITHM_EC)  {
		struct sc_ec_parameters *ecparams = &keyargs->key.u.ec.params;
		key_info->params.data = &keyargs->key.u.ec.params;
		key_info->params.free_params = sc_pkcs15init_empty_callback;
		key_info->field_length = ecparams->field_length;
		key_info->modulus_length = 0;
	}

	r = select_object_path(p15card, profile, object, &key_info->path);
	LOG_TEST_GOTO_ERR(ctx, r, "Failed to select private key object path");

	/* See if we need to select a key reference for this object */
	if (profile->ops->select_key_reference) {
		while (1) {
			sc_log(ctx, "Look for usable key reference starting from %i", key_info->key_reference);
			r = profile->ops->select_key_reference(profile, p15card, key_info);
			LOG_TEST_GOTO_ERR(ctx, r, "Failed to select card specific key reference");

			r = sc_pkcs15_find_prkey_by_reference(p15card, &key_info->path, key_info->key_reference, NULL);
			if (r == SC_ERROR_OBJECT_NOT_FOUND)   {
				sc_log(ctx, "Will use key reference %i", key_info->key_reference);
				break;
			}

			if (r != 0) {
				/* Other error trying to retrieve pin obj */
				r = SC_ERROR_TOO_MANY_OBJECTS;
				LOG_TEST_GOTO_ERR(ctx, r, "Failed to select key reference");
			}

			key_info->key_reference++;
		}
	}

	*res_obj = object;
	object = NULL;
	r = SC_SUCCESS;

err:
	if (object)
		sc_pkcs15init_free_object(object);
	LOG_FUNC_RETURN(ctx, r);
}

/*
 * Prepare secret key download, and initialize a skdf entry
 */
static int
sc_pkcs15init_init_skdf(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_skeyargs *keyargs, struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_skey_info *key_info;
	struct sc_pkcs15_object *object = NULL;
	const char	*label;
	unsigned int	usage;
	unsigned int	keybits = keyargs->value_len;
	int		r = 0, key_type;

	LOG_FUNC_CALLED(ctx);
	if (!res_obj || !keybits) {
		r = SC_ERROR_INVALID_ARGUMENTS;
		LOG_TEST_GOTO_ERR(ctx, r, "Initialize SKDF entry failed");
	}

	*res_obj = NULL;

	if ((usage = keyargs->usage) == 0) {
		usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
	}

	if ((label = keyargs->label) == NULL)
		label = DEFAULT_SECRET_KEY_LABEL;

	/* Create the skey object now.
	 * If we find out below that we're better off reusing an
	 * existing object, we'll ditch this one */
	key_type = key_pkcs15_algo(p15card, keyargs->algorithm);
	r = key_type;
	LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key type");

	object = sc_pkcs15init_new_object(key_type, label, &keyargs->auth_id, NULL);
	if (object == NULL)
		LOG_TEST_GOTO_ERR(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate new SKey object");

	key_info = (struct sc_pkcs15_skey_info *) object->data;
	key_info->usage = usage;
	key_info->native = 1;
	key_info->key_reference = 0;
	switch (keyargs->algorithm) {
	case SC_ALGORITHM_DES:
		key_info->key_type = CKK_DES;
		break;
	case SC_ALGORITHM_3DES:
		key_info->key_type = CKK_DES3;
		break;
	case SC_ALGORITHM_AES:
		key_info->key_type = CKK_AES;
		break;
	default:
		key_info->key_type = CKK_GENERIC_SECRET;
		break;
	}
	key_info->value_len = keybits;
	key_info->access_flags = keyargs->access_flags;
	/* Path is selected below */

	if (keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE) {
		key_info->access_flags &= ~SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE;
	}

	if (keyargs->session_object > 0)
	    object->session_object = 1;

	object->user_consent = keyargs->user_consent;

	/* Select a Key ID if the user didn't specify one,
	 * otherwise make sure it's compatible with our intended use */
	r = select_id(p15card, SC_PKCS15_TYPE_SKEY, &keyargs->id);
	LOG_TEST_GOTO_ERR(ctx, r, "Cannot select ID for SKey object");

	key_info->id = keyargs->id;

	r = select_object_path(p15card, profile, object, &key_info->path);
	LOG_TEST_GOTO_ERR(ctx, r, "Failed to select secret key object path");

	/* See if we need to select a key reference for this object */
	if (profile->ops->select_key_reference)
		LOG_TEST_GOTO_ERR(ctx, SC_ERROR_NOT_SUPPORTED, "SKey keyreference selection not supported");

	*res_obj = object;
	object = NULL;
	r = SC_SUCCESS;

err:
	if (object)
		sc_pkcs15init_free_object(object);
	LOG_FUNC_RETURN(ctx, r);
}

static int
_pkcd15init_set_aux_md_data(struct sc_pkcs15_card *p15card, struct sc_auxiliary_data **aux_data,
		unsigned char *guid, size_t guid_len)
{
	struct sc_context *ctx = p15card->card->ctx;
	unsigned char flags = SC_MD_CONTAINER_MAP_VALID_CONTAINER;
	char gd[SC_MD_MAX_CONTAINER_NAME_LEN + 1];
	int rv;

	LOG_FUNC_CALLED(ctx);

	if(!guid || !guid_len)
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);

	if (!aux_data)
		LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);

	if (guid_len > SC_MD_MAX_CONTAINER_NAME_LEN)
		LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);

	memset(gd, 0, sizeof(gd));
	memcpy(gd, guid, guid_len);

	if (*aux_data == NULL)   {
		rv = sc_aux_data_allocate(ctx, aux_data, NULL);
		LOG_TEST_RET(ctx, rv, "Failed to allocate aux data");
	}

	rv = sc_aux_data_set_md_guid(ctx, *aux_data, gd);
	LOG_TEST_RET(ctx, rv, "Failed to set private key CMAP record GUID");

	if (sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_PRKEY, NULL, 0) == 0)
		flags |= SC_MD_CONTAINER_MAP_DEFAULT_CONTAINER;

	rv = sc_aux_data_set_md_flags(ctx, *aux_data, flags);
	LOG_TEST_RET(ctx, rv, "Failed to set private key CMAP record flags");

	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}

/*
 * Copy gost3410 parameters (e.g. from prkey to pubkey)
 */
static int
sc_copy_gost_params(struct sc_pkcs15_gost_parameters *dst, struct sc_pkcs15_gost_parameters *src)
{
	if (!dst || !src)
		return SC_ERROR_INVALID_ARGUMENTS;

	memcpy((dst->key).value, (src->key).value, sizeof((src->key).value));
	memcpy((dst->hash).value, (src->hash).value, sizeof((src->hash).value));
	memcpy((dst->cipher).value, (src->cipher).value, sizeof((src->cipher).value));

	return SC_SUCCESS;
}

/*
 * Generate a new private key
 */
int
sc_pkcs15init_generate_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_keygen_args *keygen_args, unsigned int keybits,
		struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15init_pubkeyargs pubkey_args;
	struct sc_pkcs15_object *object = NULL;
	struct sc_pkcs15_prkey_info *key_info = NULL;
	struct sc_pkcs15_pubkey *pubkey = NULL;
	int r, caller_supplied_id = 0;

	LOG_FUNC_CALLED(ctx);
	/* check supported key size */
	r = check_keygen_params_consistency(p15card->card,
		keygen_args->prkey_args.key.algorithm, &keygen_args->prkey_args,
		&keybits);
	LOG_TEST_RET(ctx, r, "Invalid key size");

	if (check_key_compatibility(p15card, keygen_args->prkey_args.key.algorithm,
			&keygen_args->prkey_args.key, keygen_args->prkey_args.x509_usage,
			keybits, SC_ALGORITHM_ONBOARD_KEY_GEN) != SC_SUCCESS)
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot generate key with the given parameters");

	if (profile->ops->generate_key == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Key generation not supported");

	if (keygen_args->prkey_args.id.len)   {
		caller_supplied_id = 1;

		/* Make sure that private key's ID is the unique inside the PKCS#15 application */
		r = sc_pkcs15_find_prkey_by_id(p15card, &keygen_args->prkey_args.id, NULL);
		if (!r)
			LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the private key object");
		else if (r != SC_ERROR_OBJECT_NOT_FOUND)
			LOG_TEST_RET(ctx, r, "Find private key error");
	}

	/* Set up the PrKDF object */
	r = sc_pkcs15init_init_prkdf(p15card, profile, &keygen_args->prkey_args,
		&keygen_args->prkey_args.key, keybits, &object);
	LOG_TEST_RET(ctx, r, "Set up private key object error");

	key_info = (struct sc_pkcs15_prkey_info *) object->data;

	r = _pkcd15init_set_aux_md_data(p15card, &key_info->aux_data,
			keygen_args->prkey_args.guid, keygen_args->prkey_args.guid_len);
	LOG_TEST_RET(ctx, r, "Failed to set aux MD data");

	/* Set up the PuKDF info. The public key will be filled in
	 * by the card driver's generate_key function called below.
	 * Auth.ID of the public key object is left empty. */
	memset(&pubkey_args, 0, sizeof(pubkey_args));
	pubkey_args.id = keygen_args->prkey_args.id;
	pubkey_args.label = keygen_args->pubkey_label ? keygen_args->pubkey_label : object->label;
	pubkey_args.usage = keygen_args->prkey_args.usage;
	pubkey_args.x509_usage = keygen_args->prkey_args.x509_usage;

	if (keygen_args->prkey_args.key.algorithm == SC_ALGORITHM_GOSTR3410)   {
		pubkey_args.params.gost = keygen_args->prkey_args.params.gost;
		r = sc_copy_gost_params(&(pubkey_args.key.u.gostr3410.params), &(keygen_args->prkey_args.key.u.gostr3410.params));
		LOG_TEST_RET(ctx, r, "Cannot allocate GOST parameters");
	}
	else if (keygen_args->prkey_args.key.algorithm == SC_ALGORITHM_EC)   {
		pubkey_args.key.u.ec.params = keygen_args->prkey_args.key.u.ec.params;
		r = sc_copy_ec_params(&pubkey_args.key.u.ec.params, &keygen_args->prkey_args.key.u.ec.params);
		LOG_TEST_RET(ctx, r, "Cannot allocate EC parameters");
	}

	/* Generate the private key on card */
	r = profile->ops->create_key(profile, p15card, object);
	LOG_TEST_RET(ctx, r, "Cannot generate key: create key failed");

	r = profile->ops->generate_key(profile, p15card, object, &pubkey_args.key);
	LOG_TEST_RET(ctx, r, "Failed to generate key");

	/* update PrKDF entry */
	if (!caller_supplied_id)   {
		struct sc_pkcs15_id iid;

		/* Caller not supplied ID, so,
		 * if intrinsic ID can be calculated -- overwrite the native one */
		memset(&iid, 0, sizeof(iid));
		r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PUBKEY, &iid, &pubkey_args.key);
		LOG_TEST_RET(ctx, r, "Select intrinsic ID error");

		if (iid.len)
			key_info->id = iid;
	}

	pubkey = &pubkey_args.key;
	if (!pubkey->alg_id)   {
		pubkey->alg_id = calloc(1, sizeof(struct sc_algorithm_id));
		if (!pubkey->alg_id)
			LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);

		sc_init_oid(&pubkey->alg_id->oid);
		pubkey->alg_id->algorithm = pubkey->algorithm;
	}

	pubkey_args.id = key_info->id;
	r = sc_pkcs15_encode_pubkey(ctx, pubkey, &object->content.value, &object->content.len);
	LOG_TEST_RET(ctx, r, "Failed to encode public key");

	r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PRKDF, object);
	LOG_TEST_RET(ctx, r, "Failed to add generated private key object");

	if (!r && profile->ops->emu_store_data)   {
		r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
		if (r == SC_ERROR_NOT_IMPLEMENTED)
			r = SC_SUCCESS;
		LOG_TEST_RET(ctx, r, "Card specific 'store data' failed");
	}

	r = sc_pkcs15init_store_public_key(p15card, profile, &pubkey_args, NULL);
	LOG_TEST_RET(ctx, r, "Failed to store public key");

	if (res_obj)
		*res_obj = object;

	sc_pkcs15_erase_pubkey(&pubkey_args.key);

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}

/*
 * Generate a new secret key
 */
int
sc_pkcs15init_generate_secret_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_skeyargs *skey_args, struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *object = NULL;
	unsigned int keybits = skey_args->value_len;
	int r;

	LOG_FUNC_CALLED(ctx);
	/* check supported key size */
	r = check_keygen_params_consistency(p15card->card, skey_args->algorithm, NULL, &keybits);
	LOG_TEST_RET(ctx, r, "Invalid key size");

	if (check_key_compatibility(p15card, skey_args->algorithm, NULL, 0,
			keybits, SC_ALGORITHM_ONBOARD_KEY_GEN) != SC_SUCCESS)
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot generate key with the given parameters");

	if (profile->ops->generate_key == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Key generation not supported");

	if (skey_args->id.len)   {
		/* Make sure that secret key's ID is the unique inside the PKCS#15 application */
		r = sc_pkcs15_find_skey_by_id(p15card, &skey_args->id, NULL);
		if (!r)
			LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the private key object");
		else if (r != SC_ERROR_OBJECT_NOT_FOUND)
			LOG_TEST_RET(ctx, r, "Find private key error");
	}

	/* Set up the SKDF object */
	r = sc_pkcs15init_init_skdf(p15card, profile, skey_args, &object);
	LOG_TEST_RET(ctx, r, "Set up secret key object error");

	/* Generate the secret key on card */
	r = profile->ops->create_key(profile, p15card, object);
	LOG_TEST_RET(ctx, r, "Cannot generate key: create key failed");

	r = profile->ops->generate_key(profile, p15card, object, NULL);
	LOG_TEST_RET(ctx, r, "Failed to generate key");

	r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_SKDF, object);
	LOG_TEST_RET(ctx, r, "Failed to add generated secret key object");

	if (!r && profile->ops->emu_store_data)   {
		r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
		if (r == SC_ERROR_NOT_IMPLEMENTED)
			r = SC_SUCCESS;
		LOG_TEST_RET(ctx, r, "Card specific 'store data' failed");
	}

	if (res_obj)
		*res_obj = object;

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Store private key
 */
int
sc_pkcs15init_store_private_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_prkeyargs *keyargs, struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *object = NULL;
	struct sc_pkcs15_prkey key;
	struct sc_pkcs15_prkey_info *key_info = NULL;
	int keybits, r = 0;

	LOG_FUNC_CALLED(ctx);
	/* Create a copy of the key first */
	key = keyargs->key;

	r = prkey_fixup(p15card, &key);
	LOG_TEST_RET(ctx, r, "Private key data sanity check failed");

	keybits = prkey_bits(p15card, &key);
	LOG_TEST_RET(ctx, keybits, "Invalid private key size");

	/* Now check whether the card is able to handle this key */
	if (check_key_compatibility(p15card, key.algorithm, &key, keyargs->x509_usage, keybits, 0) != SC_SUCCESS) {
		/* Make sure the caller explicitly tells us to store
		 * the key as extractable. */
		if (!(keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE))
			LOG_TEST_RET(ctx, SC_ERROR_INCOMPATIBLE_KEY, "Card does not support this key for crypto. Cannot store it as non extractable.");
	}

	/* Select a intrinsic Key ID if user didn't specify one */
	r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PRKEY,
			&keyargs->id, &keyargs->key);
	LOG_TEST_RET(ctx, r, "Get intrinsic ID error");

	/* Make sure that private key's ID is the unique inside the PKCS#15 application */
	r = sc_pkcs15_find_prkey_by_id(p15card, &keyargs->id, NULL);
	if (!r)
		LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the private key object");
	else if (r != SC_ERROR_OBJECT_NOT_FOUND)
		LOG_TEST_RET(ctx, r, "Find private key error");

	/* Set up the PrKDF object */
	r = sc_pkcs15init_init_prkdf(p15card, profile, keyargs, &key, keybits, &object);
	LOG_TEST_RET(ctx, r, "Failed to initialize private key object");

	r = sc_pkcs15init_encode_prvkey_content(p15card, &key, object);
	LOG_TEST_RET(ctx, r, "Failed to encode public key");

	key_info = (struct sc_pkcs15_prkey_info *) object->data;
	r = _pkcd15init_set_aux_md_data(p15card, &key_info->aux_data, keyargs->guid, keyargs->guid_len);
	LOG_TEST_RET(ctx, r, "Failed to set aux MD data");

	if (profile->ops->create_key)
		r = profile->ops->create_key(profile, p15card, object);
	LOG_TEST_RET(ctx, r, "Card specific 'create key' failed");

	if (profile->ops->store_key)
		r = profile->ops->store_key(profile, p15card, object, &key);
	LOG_TEST_RET(ctx, r, "Card specific 'store key' failed");

	sc_pkcs15_free_object_content(object);
	r = sc_pkcs15init_encode_prvkey_content(p15card, &key, object);
	LOG_TEST_RET(ctx, r, "Failed to encode public key");

	/* Now update the PrKDF */
	r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PRKDF, object);
	LOG_TEST_RET(ctx, r, "Failed to add new private key PKCS#15 object");

	if (!r && profile->ops->emu_store_data)   {
		r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
		if (r == SC_ERROR_NOT_IMPLEMENTED)
			r = SC_SUCCESS;
		LOG_TEST_RET(ctx, r, "Card specific 'store data' failed");
	}

	if (r >= 0 && res_obj)
		*res_obj = object;

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Store a public key
 */
int
sc_pkcs15init_store_public_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_pubkeyargs *keyargs, struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *object = NULL;
	struct sc_pkcs15_pubkey_info *key_info;
	struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
	struct sc_pkcs15_pubkey key;
	struct sc_path	*path;
	const char	*label;
	unsigned int	keybits, type = 0, usage;
	int		r;

	LOG_FUNC_CALLED(ctx);
	if (!keyargs)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Store public key aborted");

	/* Create a copy of the key first */
	key = keyargs->key;

	switch (key.algorithm) {
	case SC_ALGORITHM_RSA:
		keybits = sc_pkcs15init_keybits(&key.u.rsa.modulus);
		type = SC_PKCS15_TYPE_PUBKEY_RSA;
		break;
#ifdef SC_PKCS15_TYPE_PUBKEY_DSA
	case SC_ALGORITHM_DSA:
		keybits = sc_pkcs15init_keybits(&key.u.dsa.q);
		type = SC_PKCS15_TYPE_PUBKEY_DSA;
		break;
#endif
	case SC_ALGORITHM_GOSTR3410:
		keybits = SC_PKCS15_GOSTR3410_KEYSIZE;
		type = SC_PKCS15_TYPE_PUBKEY_GOSTR3410;
		break;
	case SC_ALGORITHM_EC:
		type = SC_PKCS15_TYPE_PUBKEY_EC;

		key.u.ec.params = keyargs->key.u.ec.params;
		r = sc_pkcs15_fix_ec_parameters(ctx, &key.u.ec.params);
		LOG_TEST_RET(ctx, r, "Failed to fix EC public key parameters");

		keybits = key.u.ec.params.field_length;
		break;
	default:
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported key algorithm.");
	}

	if ((usage = keyargs->usage) == 0) {
		usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
		if (keyargs->x509_usage)
			usage = sc_pkcs15init_map_usage(keyargs->x509_usage, 0);
	}
	label = keyargs->label;
	if (!label)
		label = "Public Key";

	/* Set up the pkcs15 object. */
	object = sc_pkcs15init_new_object(type, label, &keyargs->auth_id, NULL);
	if (object == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate new public key object");

	key_info = (struct sc_pkcs15_pubkey_info *) object->data;
	key_info->usage = usage;
	key_info->modulus_length = keybits;

	if (key.algorithm == SC_ALGORITHM_GOSTR3410) {
		key_info->params.len = sizeof(*keyinfo_gostparams);
		/* FIXME: malloc() call in pkcs15init, but free() call
		 * in libopensc (sc_pkcs15_free_prkey_info) */
		key_info->params.data = malloc(key_info->params.len);
		if (!key_info->params.data) {
			r = SC_ERROR_OUT_OF_MEMORY;
			LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate GOST params");
		}
		keyinfo_gostparams = key_info->params.data;
		keyinfo_gostparams->gostr3410 = keyargs->params.gost.gostr3410;
		keyinfo_gostparams->gostr3411 = keyargs->params.gost.gostr3411;
		keyinfo_gostparams->gost28147 = keyargs->params.gost.gost28147;
	}
	else if (key.algorithm == SC_ALGORITHM_EC)   {
		key_info->field_length = keybits;
		if (key.u.ec.params.der.value) {
			key_info->params.data = malloc(key.u.ec.params.der.len);
			if (!key_info->params.data) {
				r = SC_ERROR_OUT_OF_MEMORY;
				LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate EC params");
			}
			key_info->params.len = key.u.ec.params.der.len;
			memcpy(key_info->params.data, key.u.ec.params.der.value, key.u.ec.params.der.len);
		}
	}

	/* Select a intrinsic Key ID if the user didn't specify one */
	r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PUBKEY, &keyargs->id, &key);
	LOG_TEST_GOTO_ERR(ctx, r, "Get intrinsic ID error");

	/* Select a Key ID if the user didn't specify one and there is no intrinsic ID,
	 * otherwise make sure it's unique */
	r = select_id(p15card, SC_PKCS15_TYPE_PUBKEY, &keyargs->id);
	LOG_TEST_GOTO_ERR(ctx, r, "Failed to select public key object ID");

	/* Make sure that private key's ID is the unique inside the PKCS#15 application */
	r = sc_pkcs15_find_pubkey_by_id(p15card, &keyargs->id, NULL);
	if (!r) {
		r = SC_ERROR_NON_UNIQUE_ID;
		LOG_TEST_GOTO_ERR(ctx, r, "Non unique ID of the public key object");
	} else if (r != SC_ERROR_OBJECT_NOT_FOUND)  {
		LOG_TEST_GOTO_ERR(ctx, r, "Find public key error");
	}

	key_info->id = keyargs->id;

	/* DER encode public key components */
	r = sc_pkcs15_encode_pubkey(p15card->card->ctx, &key, &object->content.value, &object->content.len);
	LOG_TEST_GOTO_ERR(ctx, r, "Encode public key error");

	r = sc_pkcs15_encode_pubkey(p15card->card->ctx, &key, &key_info->direct.raw.value, &key_info->direct.raw.len);
	LOG_TEST_GOTO_ERR(ctx, r, "RAW encode public key error");

	/* EC key are encoded as SPKI to preserve domain parameter */
	r = sc_pkcs15_encode_pubkey_as_spki(p15card->card->ctx, &key, &key_info->direct.spki.value, &key_info->direct.spki.len);
	LOG_TEST_GOTO_ERR(ctx, r, "SPKI encode public key error");

	/* Now create key file and store key */
	if (type == SC_PKCS15_TYPE_PUBKEY_EC)
		r = sc_pkcs15init_store_data(p15card, profile, object, &key_info->direct.spki, &key_info->path);
	else
		r = sc_pkcs15init_store_data(p15card, profile, object, &object->content, &key_info->path);

	path = &key_info->path;
	if (path->count == 0) {
		path->index = 0;
		path->count = -1;
	}

	/* Update the PuKDF */
	if (r >= 0)
		r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PUKDF, object);

	if (r >= 0 && res_obj)
		*res_obj = object;

	profile->dirty = 1;

err:
	if (object && r < 0)
		sc_pkcs15init_free_object(object);

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Store secret key
 */
int
sc_pkcs15init_store_secret_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15init_skeyargs *keyargs, struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *object = NULL;
	int r = 0;

	LOG_FUNC_CALLED(ctx);

	/* Now check whether the card is able to handle this key */
	if (check_key_compatibility(p15card, keyargs->algorithm, NULL, 0, keyargs->value_len, 0) != SC_SUCCESS) {
		/* Make sure the caller explicitly tells us to store
		 * the key as extractable. */
		if (!(keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE))
			LOG_TEST_RET(ctx, SC_ERROR_INCOMPATIBLE_KEY, "Card does not support this key for crypto. Cannot store it as non extractable.");
	}

#ifdef ENABLE_OPENSSL
	if (!keyargs->id.len) {
		/* Calculating intrinsic Key ID for secret key does not make
		 * sense - just generate random one */
		if (RAND_bytes(keyargs->id.value, 20) == 1)
			keyargs->id.len = 20;
	}
#endif

	/* Make sure that secret key's ID is the unique inside the PKCS#15 application */
	r = sc_pkcs15_find_skey_by_id(p15card, &keyargs->id, NULL);
	if (!r)
		LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the secret key object");
	else if (r != SC_ERROR_OBJECT_NOT_FOUND)
		LOG_TEST_RET(ctx, r, "Find secret key error");

	/* Set up the SKDF object */
	r = sc_pkcs15init_init_skdf(p15card, profile, keyargs, &object);
	LOG_TEST_RET(ctx, r, "Failed to initialize secret key object");

	if (profile->ops->create_key)
		r = profile->ops->create_key(profile, p15card, object);
	LOG_TEST_RET(ctx, r, "Card specific 'create key' failed");

	/* If no key data, only an empty EF is created. 
	 * It can be used to receive an unwrapped key later. */
	if (keyargs->key.data_len > 0) {
		if (profile->ops->store_key) {
			struct sc_pkcs15_prkey key;
			memset(&key, 0, sizeof(key));
			key.algorithm = keyargs->algorithm;
			key.u.secret = keyargs->key;
			r = profile->ops->store_key(profile, p15card, object, &key);
		}
	}
	LOG_TEST_RET(ctx, r, "Card specific 'store key' failed");

	sc_pkcs15_free_object_content(object);

	/* Now update the SKDF, unless it is a session object.
	   If we have an on card session object, we have created the actual key object on card.
	   The card handles removing it when the session is finished or during the next reset.
	   We will maintain the object in the P15 structure in memory for duration of the session,
	   but we don't want it to be written into SKDF. */
	if (!object->session_object) {
		r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_SKDF, object);
		LOG_TEST_RET(ctx, r, "Failed to add new secret key PKCS#15 object");
	}

	if (!r && profile->ops->emu_store_data && !object->session_object)   {
		r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
		if (r == SC_ERROR_NOT_IMPLEMENTED)
			r = SC_SUCCESS;
		LOG_TEST_RET(ctx, r, "Card specific 'store data' failed");
	}

	if (r >= 0 && res_obj)
		*res_obj = object;

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}

/*
 * Store a certificate
 */
int
sc_pkcs15init_store_certificate(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile,
		struct sc_pkcs15init_certargs *args,
		struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_cert_info *cert_info = NULL;
	struct sc_pkcs15_object *object = NULL;
	struct sc_pkcs15_object *key_object = NULL;
	struct sc_path existing_path;
	const char *label = NULL;
	int		r;

	LOG_FUNC_CALLED(ctx);

	memset(&existing_path, 0, sizeof(struct sc_path));

	label = args->label;
	if (!label)
		label = "Certificate";

	r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_CERT_X509,
			&args->id, &args->der_encoded);
	LOG_TEST_RET(ctx, r, "Get certificate 'intrinsic ID' error");
	sc_log(ctx, "Cert(ID:%s) rv %i", sc_pkcs15_print_id(&args->id), r);

	/* Select an ID if the user didn't specify one, otherwise make sure it's unique */
	r = select_id(p15card, SC_PKCS15_TYPE_CERT, &args->id);
	if (r == SC_ERROR_NON_UNIQUE_ID && args->update)   {
		struct sc_pkcs15_object *existing_obj = NULL;

		r = sc_pkcs15_find_object_by_id(p15card, SC_PKCS15_TYPE_CERT, &args->id, &existing_obj);
		if (!r)   {
			sc_log(ctx, "Found cert(ID:%s)", sc_pkcs15_print_id(&args->id));
			existing_path = ((struct sc_pkcs15_cert_info *)existing_obj->data)->path;

			sc_pkcs15_remove_object(p15card, existing_obj);
			sc_pkcs15_free_object(existing_obj);
		}

		r = select_id(p15card, SC_PKCS15_TYPE_CERT, &args->id);
	}
	sc_log(ctx, "Select ID Cert(ID:%s) rv %i", sc_pkcs15_print_id(&args->id), r);
	LOG_TEST_RET(ctx, r, "Select certificate ID error");

	object = sc_pkcs15init_new_object(SC_PKCS15_TYPE_CERT_X509, label, NULL, NULL);
	if (object == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Failed to allocate certificate object");
	cert_info = (struct sc_pkcs15_cert_info *) object->data;
	cert_info->id = args->id;
	cert_info->authority = args->authority;
	sc_der_copy(&object->content, &args->der_encoded);
	sc_der_copy(&cert_info->value, &args->der_encoded);

	if (existing_path.len)   {
		sc_log(ctx, "Using existing path %s", sc_print_path(&existing_path));
		cert_info->path = existing_path;
	}

	sc_log(ctx, "Store cert(%.*s,ID:%s,der(%p,%"SC_FORMAT_LEN_SIZE_T"u))",
	       (int) sizeof object->label, object->label,
	       sc_pkcs15_print_id(&cert_info->id), args->der_encoded.value,
	       args->der_encoded.len);

	if (!profile->pkcs15.direct_certificates)
		r = sc_pkcs15init_store_data(p15card, profile, object, &args->der_encoded, &cert_info->path);

	/* Now update the CDF */
	if (r >= 0)   {
		r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_CDF, object);
		/* TODO: update private key PKCS#15 object with the certificate's attributes */
	}

	if (r >= 0)   {
		r = sc_pkcs15_prkey_attrs_from_cert(p15card, object, &key_object);
		if (r)   {
			r = 0;
		}
		else if (key_object) {
			if (profile->ops->emu_update_any_df) {
				r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_UPDATE, key_object);
				if (r == SC_ERROR_NOT_SUPPORTED)
					r = SC_SUCCESS;
			}
			else {
				r = sc_pkcs15init_update_any_df(p15card, profile, key_object->df, 0);
				sc_log(ctx, "update_any_df returned %i", r);
			}
		}
	}

	if (r < 0)   {
		sc_pkcs15_remove_object(p15card, object);
		sc_pkcs15_free_object(object);
	}
	else if (res_obj)   {
		*res_obj = object;
	}

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Store a data object
 */
int
sc_pkcs15init_store_data_object(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile,
		struct sc_pkcs15init_dataargs *args,
		struct sc_pkcs15_object **res_obj)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_data_info *data_object_info;
	struct sc_pkcs15_object *object;
	struct sc_pkcs15_object *objs[32];
	const char	*label;
	int		r, i;
	unsigned int    tid = 0x01;

	LOG_FUNC_CALLED(ctx);
	if (!profile)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Missing profile");
	label = args->label;

	if (!args->id.len) {
		/* Select an ID if the user didn't specify one, otherwise
		 * make sure it's unique (even though data objects doesn't
		 * have a pkcs15 id we need one here to create a unique
		 * file id from the data file template */
		r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32);
		LOG_TEST_RET(ctx, r, "Get 'DATA' objects error");

		for (i = 0; i < r; i++) {
			unsigned char cid;
			struct sc_pkcs15_data_info *cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
			if (!cinfo->path.len)
				continue;
			cid = cinfo->path.value[cinfo->path.len - 1];
			if (cid >= tid)
				tid = cid + 1;
		}
		if (tid > 0xff)
			/* too many data objects ... */
			return SC_ERROR_TOO_MANY_OBJECTS;
		args->id.len = 1;
		args->id.value[0] = tid;
	}
	else   {
		/* in case the user specifies an id it should be at most
		 * one byte long */
		if (args->id.len > 1)
			return SC_ERROR_INVALID_ARGUMENTS;
	}

	object = sc_pkcs15init_new_object(SC_PKCS15_TYPE_DATA_OBJECT, label, &args->auth_id, NULL);
	if (object == NULL)
		return SC_ERROR_OUT_OF_MEMORY;

	data_object_info = (struct sc_pkcs15_data_info *) object->data;
	if (args->app_label != NULL)
		strlcpy(data_object_info->app_label, args->app_label, sizeof(data_object_info->app_label));
	else if (label != NULL)
		strlcpy(data_object_info->app_label, label, sizeof(data_object_info->app_label));

	data_object_info->app_oid = args->app_oid;
	sc_der_copy(&data_object_info->data, &args->der_encoded);

	r = sc_pkcs15init_store_data(p15card, profile, object, &args->der_encoded, &data_object_info->path);
	LOG_TEST_RET(ctx, r, "Store 'DATA' object error");

	/* Now update the DDF */
	r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_DODF, object);
	LOG_TEST_RET(ctx, r, "'DODF' update error");

	if (r >= 0 && res_obj)
		*res_obj = object;

	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


int
sc_pkcs15init_get_pin_reference(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile, unsigned auth_method, int reference)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_auth_info auth_info;
	struct sc_pkcs15_object *auth_objs[0x10];
	int r, ii, nn_objs;

	LOG_FUNC_CALLED(ctx);

	/* 1. Look for the corresponding pkcs15 PIN object. */

	/* Get all existing pkcs15 AUTH objects */
	r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, auth_objs, 0x10);
	LOG_TEST_RET(ctx, r, "Get PKCS#15 AUTH objects error");
	nn_objs = r;

	sc_log(ctx, "found %i auth objects; looking for AUTH object(auth_method:%i,reference:%i)",
			nn_objs, auth_method, reference);
	for (ii=0; ii<nn_objs; ii++)   {
		struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *)auth_objs[ii]->data;
		struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;

		sc_log(ctx, "check PIN(%.*s,auth_method:%i,type:%i,reference:%i,flags:%X)",
				(int) sizeof auth_objs[ii]->label, auth_objs[ii]->label, auth_info->auth_method, pin_attrs->type,
				pin_attrs->reference, pin_attrs->flags);
		/* Find out if there is AUTH pkcs15 object with given 'type' and 'reference' */
		if (auth_info->auth_method == auth_method && pin_attrs->reference == reference)
			LOG_FUNC_RETURN(ctx, pin_attrs->reference);

		if (auth_method != SC_AC_SYMBOLIC)
			continue;

		/* Translate 'SYMBOLIC' PIN reference into the pkcs#15 pinAttributes.flags
		 * 	and check for the existing pkcs15 PIN object with these flags. */
		switch (reference)   {
		case SC_PKCS15INIT_USER_PIN:
			if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
				continue;
			if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
				continue;
			break;
		case SC_PKCS15INIT_SO_PIN:
			if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
				continue;
			if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN))
				continue;
			break;
		case SC_PKCS15INIT_USER_PUK:
			if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
				continue;
			if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))
				continue;
			break;
		case SC_PKCS15INIT_SO_PUK:
			if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))
				continue;
			if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN))
				continue;
			break;
		default:
			LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid Symbolic PIN reference");
		}

		LOG_FUNC_RETURN(ctx, pin_attrs->reference);

	}

	/* 2. No existing pkcs15 PIN object
	 *	-- check if profile defines some PIN with 'reference' as PIN reference. */
	r = sc_profile_get_pin_id_by_reference(profile, auth_method, reference, &auth_info);
	if (r < 0)
		LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "PIN template not found");

	LOG_FUNC_RETURN(ctx, auth_info.attrs.pin.reference);
}


static int
sc_pkcs15init_store_data(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15_object *object, struct sc_pkcs15_der *data,
		struct sc_path *path)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file	*file = NULL;
	int		r;

	LOG_FUNC_CALLED(ctx);

	if (profile->ops->emu_store_data)   {
		r = profile->ops->emu_store_data(p15card, profile, object, data, path);
		if (r == SC_SUCCESS || r != SC_ERROR_NOT_IMPLEMENTED)
			LOG_FUNC_RETURN(ctx, r);
	}

	r = select_object_path(p15card, profile, object, path);
	LOG_TEST_RET(ctx, r, "Failed to select object path");

	r = sc_profile_get_file_by_path(profile, path, &file);
	LOG_TEST_RET(ctx, r, "Failed to get file by path");

	if (file->path.count == 0) {
		file->path.index = 0;
		file->path.count = -1;
	}

	r = sc_pkcs15init_delete_by_path(profile, p15card, &file->path);
	if (r && r != SC_ERROR_FILE_NOT_FOUND) {
		sc_file_free(file);
		LOG_TEST_RET(ctx, r, "Cannot delete file");
	}

	r = sc_pkcs15init_update_file(profile, p15card, file, data->value, data->len);

	*path = file->path;

	sc_file_free(file);
	LOG_FUNC_RETURN(ctx, r);
}

/*
 * Map X509 keyUsage extension bits to PKCS#15 keyUsage bits
 */
typedef struct {
	unsigned long x509_usage;
	unsigned int p15_usage;
} sc_usage_map;

static sc_usage_map x509_to_pkcs15_private_key_usage[16] = {
	{ SC_PKCS15INIT_X509_DIGITAL_SIGNATURE,
	  SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER },
	{ SC_PKCS15INIT_X509_NON_REPUDIATION, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION },
	{ SC_PKCS15INIT_X509_KEY_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_UNWRAP },
	{ SC_PKCS15INIT_X509_DATA_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_DECRYPT },
	{ SC_PKCS15INIT_X509_KEY_AGREEMENT, SC_PKCS15_PRKEY_USAGE_DERIVE },
	{ SC_PKCS15INIT_X509_KEY_CERT_SIGN,
	  SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER },
	{ SC_PKCS15INIT_X509_CRL_SIGN,
	  SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER }
};

static sc_usage_map x509_to_pkcs15_public_key_usage[16] = {
	{ SC_PKCS15INIT_X509_DIGITAL_SIGNATURE,
	  SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER },
	{ SC_PKCS15INIT_X509_NON_REPUDIATION, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION },
	{ SC_PKCS15INIT_X509_KEY_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_WRAP },
	{ SC_PKCS15INIT_X509_DATA_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_ENCRYPT },
	{ SC_PKCS15INIT_X509_KEY_AGREEMENT, SC_PKCS15_PRKEY_USAGE_DERIVE },
	{ SC_PKCS15INIT_X509_KEY_CERT_SIGN,
	  SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER },
	{ SC_PKCS15INIT_X509_CRL_SIGN,
	  SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER }
};


static int
sc_pkcs15init_map_usage(unsigned long x509_usage, int _private)
{
	unsigned int	p15_usage = 0, n;
	sc_usage_map   *map;

	map = _private ? x509_to_pkcs15_private_key_usage
		      : x509_to_pkcs15_public_key_usage;
	for (n = 0; n < 16; n++) {
		if (x509_usage & map[n].x509_usage)
			p15_usage |= map[n].p15_usage;
	}
	return p15_usage;
}


/*
 * Compute modulus length
 */
static size_t
sc_pkcs15init_keybits(struct sc_pkcs15_bignum *bn)
{
	unsigned int	mask, bits;

	if (!bn || !bn->len)
		return 0;
	bits = bn->len << 3;
	for (mask = 0x80; mask && !(bn->data[0] & mask); mask >>= 1)
		bits--;
	return bits;
}


/*
 * Check consistency of the key parameters.
 */
static int
check_keygen_params_consistency(struct sc_card *card,
		unsigned int alg, struct sc_pkcs15init_prkeyargs *prkey,
		unsigned int *keybits)
{
	struct sc_context *ctx = card->ctx;
	int i, rv;

	if (alg == SC_ALGORITHM_EC && prkey)   {
		struct sc_ec_parameters *ecparams = &prkey->key.u.ec.params;

		rv = sc_pkcs15_fix_ec_parameters(ctx, ecparams);
		LOG_TEST_RET(ctx, rv, "Cannot fix EC parameters");

		sc_log(ctx, "EC parameters: %s", sc_dump_hex(ecparams->der.value, ecparams->der.len));
		if (!*keybits)
			*keybits = ecparams->field_length;
	}

	for (i = 0; i < card->algorithm_count; i++) {
		struct sc_algorithm_info *info = &card->algorithms[i];

		if (info->algorithm != alg)
			continue;

		if (info->key_length != *keybits)
			continue;

		LOG_FUNC_RETURN(ctx, SC_SUCCESS);
	}

	LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}


/*
 * Check whether the card has native crypto support for this key.
 */
static int
check_key_compatibility(struct sc_pkcs15_card *p15card, unsigned int alg,
		struct sc_pkcs15_prkey *prkey, unsigned int x509_usage,
		unsigned int key_length, unsigned int flags)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_algorithm_info *info;
	unsigned int count;

	LOG_FUNC_CALLED(ctx);
	count = p15card->card->algorithm_count;
	for (info = p15card->card->algorithms; count--; info++) {
		/* don't check flags if none was specified */
		if (info->algorithm != alg || info->key_length != key_length)
			continue;
		if (flags != 0 && ((info->flags & flags) != flags))
			continue;

		if (alg == SC_ALGORITHM_RSA && prkey)   {
			if (info->u._rsa.exponent != 0 && prkey->u.rsa.exponent.len != 0) {
				struct sc_pkcs15_bignum *e = &prkey->u.rsa.exponent;
				unsigned long	exponent = 0;
				unsigned int	n;

				if (e->len > 4)
					continue;
				for (n = 0; n < e->len; n++) {
					exponent <<= 8;
					exponent |= e->data[n];
				}
				if (info->u._rsa.exponent != exponent)
					continue;
			}
		}
		else if (alg == SC_ALGORITHM_EC)   {
			if (!sc_valid_oid(&prkey->u.ec.params.id))
				if (sc_pkcs15_fix_ec_parameters(ctx, &prkey->u.ec.params))
					LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_VALID);
			if (sc_valid_oid(&info->u._ec.params.id))
				if (!sc_compare_oid(&info->u._ec.params.id, &prkey->u.ec.params.id))
					continue;
		}

		LOG_FUNC_RETURN(ctx, SC_SUCCESS);
	}

	LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_VALID);
}


/*
 * Check RSA key for consistency, and compute missing
 * CRT elements
 */
static int
prkey_fixup_rsa(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey_rsa *key)
{
	struct sc_context *ctx = p15card->card->ctx;

	if (!key->modulus.len || !key->exponent.len || !key->d.len || !key->p.len || !key->q.len) {
		sc_log(ctx, "Missing private RSA coefficient");
		return SC_ERROR_INVALID_ARGUMENTS;
	}

#ifdef ENABLE_OPENSSL

	/* Generate additional parameters.
	 * At least the GPK seems to need the full set of CRT
	 * parameters; storing just the private exponent produces
	 * invalid signatures.
	 * The cryptoflex does not seem to be able to do any sort
	 * of RSA without the full set of CRT coefficients either
	 */
	 /* We don't really need an RSA structure, only the BIGNUMs */

	if (!key->dmp1.len || !key->dmq1.len || !key->iqmp.len) {
		BIGNUM *aux;
		BN_CTX *bn_ctx;
		BIGNUM *rsa_n, *rsa_e, *rsa_d, *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp;

		rsa_n = BN_bin2bn(key->modulus.data, key->modulus.len, NULL);
		rsa_e = BN_bin2bn(key->exponent.data, key->exponent.len, NULL);
		rsa_d = BN_bin2bn(key->d.data, key->d.len, NULL);
		rsa_p = BN_bin2bn(key->p.data, key->p.len, NULL);
		rsa_q = BN_bin2bn(key->q.data, key->q.len, NULL);
		rsa_dmp1 = BN_new();
		rsa_dmq1 = BN_new();
		rsa_iqmp = BN_new();

		aux = BN_new();
		bn_ctx = BN_CTX_new();

		BN_sub(aux, rsa_q, BN_value_one());
		BN_mod(rsa_dmq1, rsa_d, aux, bn_ctx);

		BN_sub(aux, rsa_p, BN_value_one());
		BN_mod(rsa_dmp1, rsa_d, aux, bn_ctx);

		BN_mod_inverse(rsa_iqmp, rsa_q, rsa_p, bn_ctx);

		BN_clear_free(aux);
		BN_CTX_free(bn_ctx);

		/* Do not replace, only fill in missing */
		if (key->dmp1.data == NULL) {
			key->dmp1.len = BN_num_bytes(rsa_dmp1);
			key->dmp1.data = malloc(key->dmp1.len);
			if (key->dmp1.data) {
				BN_bn2bin(rsa_dmp1, key->dmp1.data);
			} else {
				key->dmp1.len = 0;
			}
		}

		if (key->dmq1.data == NULL) {
			key->dmq1.len = BN_num_bytes(rsa_dmq1);
			key->dmq1.data = malloc(key->dmq1.len);
			if (key->dmq1.data) {
				BN_bn2bin(rsa_dmq1, key->dmq1.data);
			} else {
				key->dmq1.len = 0;
			}
		}
		if (key->iqmp.data == NULL) {
			key->iqmp.len = BN_num_bytes(rsa_iqmp);
			key->iqmp.data = malloc(key->iqmp.len);
			if (key->iqmp.data) {
				BN_bn2bin(rsa_iqmp, key->iqmp.data);
			} else {
				key->iqmp.len = 0;
			}
		}

		BN_clear_free(rsa_n);
		BN_clear_free(rsa_e);
		BN_clear_free(rsa_d);
		BN_clear_free(rsa_p);
		BN_clear_free(rsa_q);
		BN_clear_free(rsa_dmp1);
		BN_clear_free(rsa_dmq1);
		BN_clear_free(rsa_iqmp);

	}
#endif
	return 0;
}


static int
prkey_fixup(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *key)
{
	switch (key->algorithm) {
	case SC_ALGORITHM_RSA:
		return prkey_fixup_rsa(p15card, &key->u.rsa);
	case SC_ALGORITHM_DSA:
	case SC_ALGORITHM_GOSTR3410:
		/* for now */
		return 0;
	}
	return 0;
}


static int
prkey_bits(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *key)
{
	struct sc_context *ctx = p15card->card->ctx;

	switch (key->algorithm) {
	case SC_ALGORITHM_RSA:
		return sc_pkcs15init_keybits(&key->u.rsa.modulus);
	case SC_ALGORITHM_DSA:
		return sc_pkcs15init_keybits(&key->u.dsa.q);
	case SC_ALGORITHM_GOSTR3410:
		if (sc_pkcs15init_keybits(&key->u.gostr3410.d) > SC_PKCS15_GOSTR3410_KEYSIZE) {
			sc_log(ctx,
			       "Unsupported key (keybits %"SC_FORMAT_LEN_SIZE_T"u)",
			       sc_pkcs15init_keybits(&key->u.gostr3410.d));
			return SC_ERROR_OBJECT_NOT_VALID;
		}
		return SC_PKCS15_GOSTR3410_KEYSIZE;
	case SC_ALGORITHM_EC:
		sc_log(ctx, "Private EC key length %"SC_FORMAT_LEN_SIZE_T"u",
		       key->u.ec.params.field_length);
		if (key->u.ec.params.field_length == 0)   {
			sc_log(ctx, "Invalid EC key length");
			return SC_ERROR_OBJECT_NOT_VALID;
		}
		return key->u.ec.params.field_length;
	}
	sc_log(ctx, "Unsupported key algorithm.");
	return SC_ERROR_NOT_SUPPORTED;
}


static int
key_pkcs15_algo(struct sc_pkcs15_card *p15card, unsigned int algorithm)
{
	struct sc_context *ctx = p15card->card->ctx;

	switch (algorithm) {
	case SC_ALGORITHM_RSA:
		return SC_PKCS15_TYPE_PRKEY_RSA;
	case SC_ALGORITHM_DSA:
		return SC_PKCS15_TYPE_PRKEY_DSA;
	case SC_ALGORITHM_GOSTR3410:
		return SC_PKCS15_TYPE_PRKEY_GOSTR3410;
	case SC_ALGORITHM_EC:
		return SC_PKCS15_TYPE_PRKEY_EC;
	case SC_ALGORITHM_DES:
		return SC_PKCS15_TYPE_SKEY_DES;
	case SC_ALGORITHM_3DES:
		return SC_PKCS15_TYPE_SKEY_3DES;
	case SC_ALGORITHM_AES:
	case SC_ALGORITHM_UNDEFINED:
		return SC_PKCS15_TYPE_SKEY_GENERIC;
	}
	sc_log(ctx, "Unsupported key algorithm.");
	return SC_ERROR_NOT_SUPPORTED;
}


static struct sc_pkcs15_df *
find_df_by_type(struct sc_pkcs15_card *p15card, unsigned int type)
{
	struct sc_pkcs15_df *df = p15card->df_list;

	while (df != NULL && df->type != type)
		df = df->next;
	return df;
}


int
sc_pkcs15init_select_intrinsic_id(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		int type, struct sc_pkcs15_id *id_out, void *data)
{
#ifndef ENABLE_OPENSSL
	LOG_FUNC_RETURN(p15card->card->ctx, SC_SUCCESS);
#else
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_pubkey *pubkey = NULL;
	unsigned id_style;
	struct sc_pkcs15_id id;
	unsigned char *id_data = NULL;
	size_t id_data_len = 0;
	int rv, allocated = 0;

	LOG_FUNC_CALLED(ctx);

	if (!id_out || !profile)
		LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);

	id_style = profile->id_style;

	/* ID already exists */
	if (id_out->len)
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);

	/* Native ID style is not intrinsic one */
	if (id_style == SC_PKCS15INIT_ID_STYLE_NATIVE)
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);

	memset(&id, 0, sizeof(id));
	/* Get PKCS15 public key */
	switch(type)   {
	case SC_PKCS15_TYPE_CERT_X509:
		rv = sc_pkcs15_pubkey_from_cert(ctx, (struct sc_pkcs15_der *)data, &pubkey);
		LOG_TEST_RET(ctx, rv, "X509 parse error");
		allocated = 1;
		break;
	case SC_PKCS15_TYPE_PRKEY:
		rv = sc_pkcs15_pubkey_from_prvkey(ctx, (struct sc_pkcs15_prkey *)data, &pubkey);
		LOG_TEST_RET(ctx, rv, "Cannot get public key");
		allocated = 1;
		break;
	case SC_PKCS15_TYPE_PUBKEY:
		pubkey = (struct sc_pkcs15_pubkey *)data;
		allocated = 0;
		break;
	default:
		sc_log(ctx, "Intrinsic ID is not implemented for the object type 0x%X", type);
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);
	}

	/* Skip silently if key is not initialized. */
	if (pubkey->algorithm == SC_ALGORITHM_RSA && !pubkey->u.rsa.modulus.len)
		goto done;
	else if (pubkey->algorithm == SC_ALGORITHM_DSA && !pubkey->u.dsa.pub.data)
		goto done;
	else if (pubkey->algorithm == SC_ALGORITHM_GOSTR3410 &&
			!pubkey->u.gostr3410.xy.data)
		goto done;
	else if (pubkey->algorithm == SC_ALGORITHM_EC && !pubkey->u.ec.ecpointQ.value)
		goto done;

	/* In Mozilla 'GOST R 34.10' is not yet supported.
	 * So, switch to the ID recommended by RFC2459 */
	if (pubkey->algorithm == SC_ALGORITHM_GOSTR3410 && id_style == SC_PKCS15INIT_ID_STYLE_MOZILLA)
		id_style = SC_PKCS15INIT_ID_STYLE_RFC2459;

	switch (id_style)  {
	case SC_PKCS15INIT_ID_STYLE_MOZILLA:
		if (pubkey->algorithm == SC_ALGORITHM_RSA)
			SHA1(pubkey->u.rsa.modulus.data, pubkey->u.rsa.modulus.len, id.value);
		else if (pubkey->algorithm == SC_ALGORITHM_DSA)
			SHA1(pubkey->u.dsa.pub.data, pubkey->u.dsa.pub.len, id.value);
		else if (pubkey->algorithm == SC_ALGORITHM_EC)
			/* ID should be SHA1 of the X coordinate according to PKCS#15 v1.1 */
			/* skip the 04 tag and get the X component */
			SHA1(pubkey->u.ec.ecpointQ.value+1, (pubkey->u.ec.ecpointQ.len - 1) / 2, id.value);
		else
			goto done;

		id.len = SHA_DIGEST_LENGTH;
		break;
	case SC_PKCS15INIT_ID_STYLE_RFC2459:
		rv = sc_pkcs15_encode_pubkey(ctx, pubkey, &id_data, &id_data_len);
		LOG_TEST_GOTO_ERR(ctx, rv, "Encoding public key error");

		if (!id_data || !id_data_len) {
			rv = SC_ERROR_INTERNAL;
			LOG_TEST_GOTO_ERR(ctx, rv, "Encoding public key error");
		}

		SHA1(id_data, id_data_len, id.value);
		id.len = SHA_DIGEST_LENGTH;

		break;
	default:
		sc_log(ctx, "Unsupported ID style: %i", id_style);
		rv = SC_ERROR_NOT_SUPPORTED;
		LOG_TEST_GOTO_ERR(ctx, rv, "Non supported ID style");
	}

done:
	memcpy(id_out, &id, sizeof(*id_out));
	rv = id_out->len;
err:
	if (id_data)
		free(id_data);
	if (allocated)
		sc_pkcs15_free_pubkey(pubkey);

	LOG_FUNC_RETURN(ctx, rv);
#endif
}


static int
select_id(struct sc_pkcs15_card *p15card, int type, struct sc_pkcs15_id *id)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_id unused_id;
	struct sc_pkcs15_object *obj;
	unsigned int nid = DEFAULT_ID;
	int r;

	LOG_FUNC_CALLED(ctx);
	/* If the user provided an ID, make sure we can use it */
	if (id->len != 0) {
		r = sc_pkcs15_find_object_by_id(p15card, type, id, &obj);

		if (r == SC_ERROR_OBJECT_NOT_FOUND)
			r = 0;
		else if (!r)
			r = SC_ERROR_NON_UNIQUE_ID;

		LOG_FUNC_RETURN(ctx, r);
	}

	memset(&unused_id, 0, sizeof(unused_id));
	while (nid < 255) {
		id->value[0] = nid++;
		id->len = 1;

		r = sc_pkcs15_find_object_by_id(p15card, type, id, &obj);
		if (r == SC_ERROR_OBJECT_NOT_FOUND) {
			/* We don't have an object of that type yet.
			 * If we're allocating a PRKEY object, make
			 * sure there's no conflicting pubkey or cert
			 * object either. */
			if (type == SC_PKCS15_TYPE_PRKEY) {
				struct sc_pkcs15_search_key search_key;

				memset(&search_key, 0, sizeof(search_key));
				search_key.class_mask = SC_PKCS15_SEARCH_CLASS_PUBKEY | SC_PKCS15_SEARCH_CLASS_CERT;
				search_key.id = id;

				r = sc_pkcs15_search_objects(p15card, &search_key, NULL, 0);
				/* If there is a pubkey or cert with
				 * this ID, skip it. */
				if (r > 0)
					continue;
			}
			if (!unused_id.len)
				unused_id = *id;
			continue;
		}
	}

	if (unused_id.len) {
		*id = unused_id;
		LOG_FUNC_RETURN(ctx, 0);
	}

	LOG_FUNC_RETURN(ctx, SC_ERROR_TOO_MANY_OBJECTS);
}


/*
 * Select a path for a new object
 *  1.	If the object is to be protected by a PIN, use the path
 *	given in the PIN auth object
 *  2.	Otherwise, use the path of the application DF
 *  3.	If the profile defines a key-dir template, the new object
 *	should go into a subdirectory of the selected DF:
 *	Instantiate the template, using the ID of the new object
 *	to uniquify the path. Inside the instantiated template,
 *	look for a file corresponding to the type of object we
 *	wish to create ("private-key", "public-key" etc).
 */
static const char *
get_template_name_from_object (struct sc_pkcs15_object *obj)
{
	switch (obj->type & SC_PKCS15_TYPE_CLASS_MASK) {
	case SC_PKCS15_TYPE_PRKEY:
		return "private-key";
	case SC_PKCS15_TYPE_PUBKEY:
		return "public-key";
	case SC_PKCS15_TYPE_SKEY:
		return "secret-key";
	case SC_PKCS15_TYPE_CERT:
		return "certificate";
	case SC_PKCS15_TYPE_DATA_OBJECT:
		if (obj->flags & SC_PKCS15_CO_FLAG_PRIVATE)
			return "privdata";
		else
			return "data";
	}

	return NULL;
}


static int
get_object_path_from_object (struct sc_pkcs15_object *obj,
		struct sc_path *ret_path)
{
	if (!ret_path)
		return SC_ERROR_INVALID_ARGUMENTS;

	memset(ret_path, 0, sizeof(struct sc_path));

	switch(obj->type & SC_PKCS15_TYPE_CLASS_MASK)   {
	case SC_PKCS15_TYPE_PRKEY:
		*ret_path = ((struct sc_pkcs15_prkey_info *)obj->data)->path;
		return SC_SUCCESS;
	case SC_PKCS15_TYPE_PUBKEY:
		*ret_path = ((struct sc_pkcs15_pubkey_info *)obj->data)->path;
		return SC_SUCCESS;
	case SC_PKCS15_TYPE_SKEY:
		*ret_path = ((struct sc_pkcs15_skey_info *)obj->data)->path;
		return SC_SUCCESS;
	case SC_PKCS15_TYPE_CERT:
		*ret_path = ((struct sc_pkcs15_cert_info *)obj->data)->path;
		return SC_SUCCESS;
	case SC_PKCS15_TYPE_DATA_OBJECT:
		*ret_path = ((struct sc_pkcs15_data_info *)obj->data)->path;
		return SC_SUCCESS;
	case SC_PKCS15_TYPE_AUTH:
		*ret_path = ((struct sc_pkcs15_auth_info *)obj->data)->path;
		return SC_SUCCESS;
	}
	return SC_ERROR_NOT_SUPPORTED;
}


static int
select_object_path(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15_object *obj, struct sc_path *path)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file	*file;
	struct sc_pkcs15_object	*objs[32];
	struct sc_pkcs15_id indx_id;
	struct sc_path obj_path;
	int ii, r, nn_objs, indx;
	const char *name;

	LOG_FUNC_CALLED(ctx);
	r = sc_pkcs15_get_objects(p15card, obj->type & SC_PKCS15_TYPE_CLASS_MASK, objs, sizeof(objs)/sizeof(objs[0]));
	LOG_TEST_RET(ctx, r, "Get PKCS#15 objects error");
	nn_objs = r;

	/* For cards with a pin-domain profile, we need
	 * to put the key below the DF of the specified PIN
	 */
	memset(path, 0, sizeof(*path));
	if (obj->auth_id.len && profile->pin_domains != 0) {
		r = sc_pkcs15init_get_pin_path(p15card, &obj->auth_id, path);
		LOG_TEST_RET(ctx, r, "Cannot get PIN path");
	}
	else {
		*path = profile->df_info->file->path;
	}

	/* If the profile specifies a key directory template,
	 * instantiate it now and create the DF
	 */
	name = get_template_name_from_object (obj);
	if (!name)
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);

	sc_log(ctx, "key-domain.%s @%s (auth_id.len=%"SC_FORMAT_LEN_SIZE_T"u)",
	       name, sc_print_path(path), obj->auth_id.len);

	indx_id.len = 1;
	for (indx = TEMPLATE_INSTANTIATE_MIN_INDEX; indx <= TEMPLATE_INSTANTIATE_MAX_INDEX; indx++)   {
		indx_id.value[0] = indx;
		r = sc_profile_instantiate_template(profile, "key-domain", path, name, &indx_id, &file);
		if (r == SC_ERROR_TEMPLATE_NOT_FOUND)   {
			/* No template in 'key-domain' -- try to instantiate the template-'object name'
			 * outside of the 'key-domain' scope. */
			char t_name[0x40];

			snprintf(t_name, sizeof(t_name), "template-%s", name);
			sc_log(ctx, "get instance %i of '%s'", indx, t_name);
			r = sc_profile_get_file_instance(profile, t_name, indx, &file);
			if (r == SC_ERROR_FILE_NOT_FOUND)
				LOG_FUNC_RETURN(ctx, SC_SUCCESS);
		}
		LOG_TEST_RET(ctx, r, "Template instantiation error");

		if (file->type == SC_FILE_TYPE_BSO)
			break;

		sc_log(ctx, "instantiated template path %s", sc_print_path(&file->path));
		for (ii=0; ii<nn_objs; ii++)   {
			r = get_object_path_from_object(objs[ii], &obj_path);
			LOG_TEST_RET(ctx, r, "Failed to get object path from pkcs15 object");

			if (obj_path.len != file->path.len)
				break;

			if (!memcmp(obj_path.value, file->path.value, obj_path.len))
				break;
		}

		if (ii==nn_objs)
			break;

		if (obj_path.len != file->path.len)
			break;

		sc_file_free(file);

		indx_id.value[0] += 1;
	}

	if (indx > TEMPLATE_INSTANTIATE_MAX_INDEX)
		LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Template instantiation error");

	*path = file->path;
	sc_file_free(file);

	sc_log(ctx, "returns object path '%s'", sc_print_path(path));
	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}

/*
 * Update EF(DIR)
 */
static int
sc_pkcs15init_update_dir(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile,
		struct sc_app_info *app)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_card	*card = p15card->card;
	int r, retry = 1;

	LOG_FUNC_CALLED(ctx);
	if (profile->ops->emu_update_dir)   {
		r = profile->ops->emu_update_dir(profile, p15card, app);
		LOG_FUNC_RETURN(ctx, r);
	}

	do {
		struct sc_file	*dir_file;
		struct sc_path	path;

		r = sc_enum_apps(card);
		if (r != SC_ERROR_FILE_NOT_FOUND)
			break;
		/* DIR file is not yet created. */

		sc_format_path("3F002F00", &path);
		r = sc_profile_get_file_by_path(profile, &path, &dir_file);
		LOG_TEST_RET(ctx, r, "DIR file not defined in profile");

		/* Create DIR file */
		r = sc_pkcs15init_update_file(profile, p15card, dir_file, NULL, 0);
		sc_file_free(dir_file);
	} while (retry--);

	if (r >= 0) {
		card->app[card->app_count++] = app;
		r = sc_update_dir(card, NULL);
	}
	LOG_FUNC_RETURN(ctx, r);
}


static int
sc_pkcs15init_update_tokeninfo(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
{
	struct sc_context *ctx = p15card->card->ctx;
	unsigned char	*buf = NULL;
	size_t		size;
	int		rv;

	LOG_FUNC_CALLED(ctx);

	/* set lastUpdate field */
	if (p15card->tokeninfo->last_update.gtime != NULL)   {
		free(p15card->tokeninfo->last_update.gtime);
		p15card->tokeninfo->last_update.gtime = NULL;
	}
	rv = sc_pkcs15_get_generalized_time(ctx, &p15card->tokeninfo->last_update.gtime);
	LOG_TEST_RET(ctx, rv, "Cannot allocate generalized time string");

	if (profile->ops->emu_update_tokeninfo)
		return profile->ops->emu_update_tokeninfo(profile, p15card, p15card->tokeninfo);

	if (!p15card->file_tokeninfo)   {
		sc_log(ctx, "No TokenInfo to update");
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);
	}

	rv = sc_pkcs15_encode_tokeninfo(ctx, p15card->tokeninfo, &buf, &size);
	if (rv >= 0)
		rv = sc_pkcs15init_update_file(profile, p15card, p15card->file_tokeninfo, buf, size);
	if (buf)
		free(buf);

	LOG_FUNC_RETURN(ctx, rv);
}


static int
sc_pkcs15init_update_lastupdate(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
{
	struct sc_context *ctx = p15card->card->ctx;
	int		r;

	LOG_FUNC_CALLED(ctx);
	if (p15card->tokeninfo->last_update.path.len)    {
		static const struct sc_asn1_entry c_asn1_last_update[2] = {
		        { "generalizedTime",    SC_ASN1_GENERALIZEDTIME, SC_ASN1_TAG_GENERALIZEDTIME,   SC_ASN1_OPTIONAL, NULL, NULL },
			{ NULL, 0, 0, 0, NULL, NULL }
		};
		struct sc_asn1_entry asn1_last_update[2];
		size_t lupdate_len;
		struct sc_file *file = NULL;
		struct sc_pkcs15_last_update *last_update = &p15card->tokeninfo->last_update;
		unsigned char *buf = NULL;
		size_t buflen;

		/* update 'lastUpdate' file */
		if (last_update->gtime != NULL)
			free(last_update->gtime);
		r = sc_pkcs15_get_generalized_time(ctx, &last_update->gtime);
		LOG_TEST_RET(ctx, r, "Cannot allocate generalized time string");

		sc_copy_asn1_entry(c_asn1_last_update, asn1_last_update);
		lupdate_len = strlen(last_update->gtime);
		sc_format_asn1_entry(asn1_last_update + 0, last_update->gtime, &lupdate_len, 1);

		r = sc_asn1_encode(ctx, asn1_last_update, &buf, &buflen);
		LOG_TEST_RET(ctx, r, "select object path failed");

		r = sc_select_file(p15card->card, &last_update->path, &file);
		LOG_TEST_RET(ctx, r, "select object path failed");

		r = sc_pkcs15init_update_file(profile, p15card, file, buf, buflen);
		sc_file_free(file);
		if (buf)
			free(buf);
		LOG_TEST_RET(ctx, r, "Cannot update 'LastUpdate' file");
		LOG_FUNC_RETURN(ctx, r);
	}

	r = sc_pkcs15init_update_tokeninfo(p15card, profile);
	LOG_FUNC_RETURN(ctx, r);
}


static int
sc_pkcs15init_update_odf(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
{
	struct sc_context	*ctx = p15card->card->ctx;
	unsigned char	*buf = NULL;
	size_t		size;
	int		r;

	LOG_FUNC_CALLED(ctx);
	r = sc_pkcs15_encode_odf(ctx, p15card, &buf, &size);
	if (r >= 0)
		r = sc_pkcs15init_update_file(profile, p15card, p15card->file_odf, buf, size);
	if (buf)
		free(buf);
	LOG_FUNC_RETURN(ctx, r);
}

/*
 * Update any PKCS15 DF file (except ODF and DIR)
 */
int
sc_pkcs15init_update_any_df(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile,
		struct sc_pkcs15_df *df,
		int is_new)
{
	struct sc_context	*ctx = p15card->card->ctx;
	struct sc_card	*card = p15card->card;
	struct sc_file	*file = NULL;
	unsigned char	*buf = NULL;
	size_t		bufsize;
	int		update_odf = is_new, r = 0;

	LOG_FUNC_CALLED(ctx);
	if (!df)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "DF missing");

	r = sc_profile_get_file_by_path(profile, &df->path, &file);
	if (r < 0 || file == NULL)
		sc_select_file(card, &df->path, &file);

	r = sc_pkcs15_encode_df(card->ctx, p15card, df, &buf, &bufsize);
	if (r >= 0) {
		r = sc_pkcs15init_update_file(profile, p15card, file, buf, bufsize);

		/* For better performance and robustness, we want
		 * to note which portion of the file actually
		 * contains valid data.
		 *
		 * This is particularly useful if we store certificates
		 * directly in the CDF - we may want to make the CDF
		 * fairly big, without having to read the entire file
		 * every time we parse the CDF.
		 */
		if (profile->pkcs15.encode_df_length) {
			df->path.count = bufsize;
			df->path.index = 0;
			update_odf = 1;
		}
		free(buf);
	}
	sc_file_free(file);

	LOG_TEST_RET(ctx, r, "Failed to encode or update xDF");

	/* Now update the ODF if we have to */
	if (update_odf)
		r = sc_pkcs15init_update_odf(p15card, profile);
	LOG_TEST_RET(ctx, r, "Failed to encode or update ODF");

	LOG_FUNC_RETURN(ctx, r > 0 ? SC_SUCCESS : r);
}

/*
 * Add an object to one of the pkcs15 directory files.
 */
int
sc_pkcs15init_add_object(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		unsigned int df_type, struct sc_pkcs15_object *object)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_df *df;
	int is_new = 0, r = 0, object_added = 0;

	LOG_FUNC_CALLED(ctx);
	sc_log(ctx, "add object %p to DF of type %u", object, df_type);

	df = find_df_by_type(p15card, df_type);
	if (df == NULL) {
		struct sc_file	*file;
		file = profile->df[df_type];
		if (file == NULL) {
			sc_log(ctx, "Profile doesn't define a DF file %u", df_type);
			LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "DF not found in profile");
		}
		sc_pkcs15_add_df(p15card, df_type, &file->path);
		df = find_df_by_type(p15card, df_type);
		assert(df != NULL);
		is_new = 1;

		/* Mark the df as enumerated, so libopensc doesn't try
		 * to load the file at a most inconvenient moment */
		df->enumerated = 1;
	}

	if (object == NULL) {
		sc_log(ctx, "Add nothing; just instantiate this directory file");
	}
	else if (object->df == NULL) {
		sc_log(ctx, "Append object");
		object->df = df;
		r = sc_pkcs15_add_object(p15card, object);
		LOG_TEST_RET(ctx, r, "Failed to add pkcs15 object");
		object_added = 1;
	}
	else {
		sc_log(ctx, "Reuse existing object");
		assert(object->df == df);
	}

	if (profile->ops->emu_update_any_df)
		r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_CREATE, object);
	else
		r = sc_pkcs15init_update_any_df(p15card, profile, df, is_new);

	if (r < 0 && object_added)
		sc_pkcs15_remove_object(p15card, object);

	LOG_FUNC_RETURN(ctx, r > 0 ? SC_SUCCESS : r);
}


struct sc_pkcs15_object *
sc_pkcs15init_new_object(int type, const char *label, struct sc_pkcs15_id *auth_id, void *data)
{
	struct sc_pkcs15_object	*object;
	unsigned int data_size = 0;

	object = calloc(1, sizeof(*object));
	if (object == NULL)
		return NULL;
	object->type = type;

	switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
	case SC_PKCS15_TYPE_AUTH:
		object->flags = DEFAULT_PIN_FLAGS;
		data_size = sizeof(struct sc_pkcs15_auth_info);
		break;
	case SC_PKCS15_TYPE_PRKEY:
		object->flags = DEFAULT_PRKEY_FLAGS;
		data_size = sizeof(struct sc_pkcs15_prkey_info);
		break;
	case SC_PKCS15_TYPE_SKEY:
		object->flags = DEFAULT_SKEY_FLAGS;
		data_size = sizeof(struct sc_pkcs15_skey_info);
		break;
	case SC_PKCS15_TYPE_PUBKEY:
		object->flags = DEFAULT_PUBKEY_FLAGS;
		data_size = sizeof(struct sc_pkcs15_pubkey_info);
		break;
	case SC_PKCS15_TYPE_CERT:
		object->flags = DEFAULT_CERT_FLAGS;
		data_size = sizeof(struct sc_pkcs15_cert_info);
		break;
	case SC_PKCS15_TYPE_DATA_OBJECT:
		object->flags = DEFAULT_DATA_FLAGS;
		if (auth_id->len != 0)
			object->flags |= SC_PKCS15_CO_FLAG_PRIVATE;
		data_size = sizeof(struct sc_pkcs15_data_info);
		break;
	}

	if (data_size) {
		object->data = calloc(1, data_size);
		if (data)
			memcpy(object->data, data, data_size);
	}

	if (label)
		strlcpy(object->label, label, sizeof(object->label));
	if (auth_id)
		object->auth_id = *auth_id;

	return object;
}


void
sc_pkcs15init_free_object(struct sc_pkcs15_object *object)
{
	if (object) {
		free(object->data);
		free(object);
	}
}


int
sc_pkcs15init_change_attrib(struct sc_pkcs15_card *p15card, struct sc_profile *profile, struct sc_pkcs15_object *object,
		int new_attrib_type, void *new_value, int new_len)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_card	*card = p15card->card;
	unsigned char	*buf = NULL;
	size_t		bufsize;
	int		df_type, r = 0;
	struct sc_pkcs15_df *df;
	struct sc_pkcs15_id new_id = *((struct sc_pkcs15_id *) new_value);

	LOG_FUNC_CALLED(ctx);
	if (object == NULL || object->df == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot change attribute");
	df_type = object->df->type;

	df = find_df_by_type(p15card, df_type);
	if (df == NULL)
		LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot change attribute");

	sc_log(ctx, "type of attribute to change %i; DF type %i", new_attrib_type, df_type);
	switch(new_attrib_type)   {
	case P15_ATTR_TYPE_LABEL:
		if (new_len >= SC_PKCS15_MAX_LABEL_SIZE)
			LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "New label too long");
		memcpy(object->label, new_value, new_len);
		object->label[new_len] = '\0';
		break;
	case P15_ATTR_TYPE_ID:
		switch(df_type) {
		case SC_PKCS15_PRKDF:
			((struct sc_pkcs15_prkey_info *) object->data)->id = new_id;
			break;
		case SC_PKCS15_PUKDF:
		case SC_PKCS15_PUKDF_TRUSTED:
			((struct sc_pkcs15_pubkey_info *) object->data)->id = new_id;
			break;
		case SC_PKCS15_SKDF:
			((struct sc_pkcs15_skey_info *) object->data)->id = new_id;
			break;
		case SC_PKCS15_CDF:
		case SC_PKCS15_CDF_TRUSTED:
		case SC_PKCS15_CDF_USEFUL:
			((struct sc_pkcs15_cert_info *) object->data)->id = new_id;
			break;
		default:
			LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot change ID attribute");
		}
		break;
	case P15_ATTR_TYPE_VALUE:
		switch(df_type) {
		case SC_PKCS15_DODF: {
			u8 *nv;
			struct sc_pkcs15_data_info *info = (struct sc_pkcs15_data_info *) object->data;
			struct sc_path old_data_path = info->path;
			struct sc_path new_data_path;
			struct sc_pkcs15_der new_data;
			new_data.len = new_len;
			new_data.value = (u8 *) new_value;
			
			/* save new data as a new data file on token */
			r = sc_pkcs15init_store_data(p15card, profile, object, &new_data, &new_data_path);
			profile->dirty = 1;
			LOG_TEST_RET(ctx, r, "Failed to store new data");

			nv = (u8 *) malloc (new_len * sizeof(u8));
			if (!nv) {
				LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
			}
			memcpy(nv, new_value, new_len * sizeof(u8));
			free(info->data.value);
			/*  set object members to represent new CKA_VALUE value,
				new path will be written to DODF later in this function*/
			info->data.len = new_len;
			info->data.value = nv;
			info->path = new_data_path;
			
			/* delete old data file from token */
			r = sc_pkcs15init_delete_by_path(profile, p15card, &old_data_path);
			LOG_TEST_RET(ctx, r, "Failed to delete old data");
			break;
		}
		default:
			LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot change value attribute");
		}
		break;
	default:
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only 'LABEL' or 'ID' or 'VALUE'(for data objects) attributes can be changed");
	}

	if (profile->ops->emu_update_any_df)   {
		r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_CREATE, object);
		LOG_TEST_RET(ctx, r, "Card specific DF update failed");
	}
	else   {
		r = sc_pkcs15_encode_df(card->ctx, p15card, df, &buf, &bufsize);
		if (r >= 0) {
			struct sc_file *file = NULL;

			r = sc_profile_get_file_by_path(profile, &df->path, &file);
			if (r < 0)
				free(buf);
			LOG_TEST_RET(ctx, r, "Cannot instantiate file by path");

			r = sc_pkcs15init_update_file(profile, p15card, file, buf, bufsize);
			free(buf);
			sc_file_free(file);
		}
	}

	if (r > 0)
		r = 0;
	LOG_FUNC_RETURN(ctx, r);
}


int
sc_pkcs15init_delete_object(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
		struct sc_pkcs15_object *obj)
{
	struct sc_context	*ctx = p15card->card->ctx;
	struct sc_file *file = NULL;
	struct sc_path path;
	struct sc_pkcs15_df *df;
	int r = 0, stored_in_ef = 0;

	LOG_FUNC_CALLED(ctx);
	r = get_object_path_from_object(obj, &path);
	LOG_TEST_RET(ctx, r, "Failed to get object path");

	sc_log(ctx, "delete object(type:%X) with path(type:%X,%s)", obj->type, path.type, sc_print_path(&path));

	if (profile->ops->delete_object != NULL) {
		/* If there's a card-specific way to delete objects, use it. */
		r = profile->ops->delete_object(profile, p15card, obj, &path);
		if (r != SC_ERROR_NOT_SUPPORTED)
			LOG_TEST_RET(ctx, r, "Card specific delete object failed");
	}

	if (profile->ops->delete_object == NULL || r == SC_ERROR_NOT_SUPPORTED)  {
		if (path.len || path.aid.len)   {
			r = sc_select_file(p15card->card, &path, &file);
			if (r != SC_ERROR_FILE_NOT_FOUND)
				LOG_TEST_RET(ctx, r, "select object path failed");

			stored_in_ef = (file->type != SC_FILE_TYPE_DF);
			sc_file_free(file);
		}

		/* If the object is stored in a normal EF, try to delete the EF. */
		if (r == SC_SUCCESS && stored_in_ef) {
			r = sc_pkcs15init_delete_by_path(profile, p15card, &path);
			LOG_TEST_RET(ctx, r, "Failed to delete object by path");
		}
	}

	if (profile->ops->emu_update_any_df)   {
		r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_ERASE, obj);
		LOG_TEST_RET(ctx, r, "'ERASE' update DF failed");
	}

	/* Get the DF we're part of. If there's no DF, fine, we haven't been added yet. */
	df = obj->df;
	if (df)   {
		/* Unlink the object and update the DF */
		sc_pkcs15_remove_object(p15card, obj);
		sc_pkcs15_free_object(obj);
	}

	if (!profile->ops->emu_update_any_df)
		r = sc_pkcs15init_update_any_df(p15card, profile, df, 0);

	/* mark card as dirty */
	profile->dirty = 1;

	LOG_FUNC_RETURN(ctx, r);
}


int
sc_pkcs15init_update_certificate(struct sc_pkcs15_card *p15card,
	struct sc_profile *profile, struct sc_pkcs15_object *obj,
	const unsigned char *rawcert, size_t certlen)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file *file = NULL;
	struct sc_path *path = &((struct sc_pkcs15_cert_info *)obj->data)->path;
	int r;

	LOG_FUNC_CALLED(ctx);
	r = sc_select_file(p15card->card, path, &file);
	LOG_TEST_RET(ctx, r, "Failed to select cert file");

	/* If the new cert doesn't fit in the EF, delete it and make the same, but bigger EF */
	if (file->size != certlen) {
		struct sc_file *parent = NULL;

		r = sc_pkcs15init_delete_by_path(profile, p15card, path);
		if (r < 0)
			goto done;

		file->size = certlen;

		r = do_select_parent(profile, p15card, file, &parent);
		if (r < 0)
			goto done;

		r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_CREATE);
		sc_file_free(parent);
		if (r < 0)   {
			sc_log(ctx, "'CREATE' authentication failed");
			goto done;
		}

		/* ensure we are in the correct lifecycle */
		r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
		if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
			goto done;

		r = sc_create_file(p15card->card, file);
		if (r < 0)   {
			sc_log(ctx, "Cannot create cert file");
			goto done;
		}
	}

	if (!sc_file_get_acl_entry(file, SC_AC_OP_UPDATE))   {
		struct sc_path tmp_path;

		/* FCI of selected cert file do not contains ACLs.
		 * For the 'UPDATE' authentication use instead sc_file
		 *	instantiated from card profile with default ACLs. */
		sc_file_free(file);

		r = select_object_path(p15card, profile, obj, &tmp_path);
		if (r < 0)   {
			sc_log(ctx, "Select object path error");
			goto done;
		}

		r = sc_profile_get_file_by_path(profile, path, &file);
		if (r < 0)   {
			sc_log(ctx, "Cannot instantiate cert file");
			goto done;
		}
	}

	/* Write the new cert */
	r = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_UPDATE);
	if (r < 0)   {
		sc_log(ctx, "'UPDATE' authentication failed");
		goto done;
	}

	r = sc_select_file(p15card->card, path, NULL);
	if (r < 0)
		goto done;

	r = sc_update_binary(p15card->card, 0, rawcert, certlen, 0);
	if (r < 0)
		goto done;

	/* Fill the remaining space in the EF (if any) with zeros */
	if (certlen < file->size) {
		unsigned char *tmp = calloc(file->size - certlen, 1);
		if (tmp == NULL) {
			r = SC_ERROR_OUT_OF_MEMORY;
			goto done;
		}
		r = sc_update_binary(p15card->card, certlen, tmp, file->size - certlen, 0);
		free(tmp);
		if (r < 0)
			sc_log(ctx, "Update cert file error");
	}

	if (r >= 0) {
		/* Update the CDF entry */
		path = &((struct sc_pkcs15_cert_info *)obj->data)->path;
		if (file->size != certlen) {
			path->index = 0;
			path->count = certlen;
		}
		else   {
			path->count = -1;
		}

		if (profile->ops->emu_update_any_df) {
			r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_UPDATE, obj);
			if (r == SC_ERROR_NOT_SUPPORTED)
				r = SC_SUCCESS;
		}
		else {
			r = sc_pkcs15init_update_any_df(p15card, profile, obj->df, 0);
		}

		if (r < 0)
			sc_log(ctx, "Failed to update CDF");
	}

	/* mark card as dirty */
	profile->dirty = 1;

done:
	sc_file_free(file);

	LOG_FUNC_RETURN(ctx, r);
}


static const char *
get_pin_ident_name(int type, int reference)
{
	switch (type)   {
	case SC_AC_CHV:
		return "PIN";
	case SC_AC_PRO:
		return "secure messaging key";
	case SC_AC_AUT:
		return "authentication key";
	case SC_AC_SEN:
		return "security environment";
	case SC_AC_IDA:
		return "PKCS#15 reference";
	case SC_AC_SCB:
		return "SCB byte in IAS/ECC";
	case SC_AC_SYMBOLIC:
		switch (reference) {
	        case SC_PKCS15INIT_USER_PIN:
			return "user PIN";
		case SC_PKCS15INIT_SO_PIN:
			return "SO PIN";
	        case SC_PKCS15INIT_USER_PUK:
			return "user PUK";
		case SC_PKCS15INIT_SO_PUK:
			return "SO PUK";
		}
	}
	return "authentication data";
}


static int
sc_pkcs15init_get_transport_key(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
		int type, int reference, unsigned char *pinbuf, size_t *pinsize)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *pin_obj = NULL;
	struct sc_pkcs15_auth_info auth_info;
	struct sc_cardctl_default_key data;
	size_t		defsize = 0;
	unsigned char	defbuf[0x100];
	int rv;

	LOG_FUNC_CALLED(ctx);

	data.method = type;
	data.key_ref = reference;
	data.len = sizeof(defbuf);
	data.key_data = defbuf;
	rv = sc_card_ctl(p15card->card, SC_CARDCTL_GET_DEFAULT_KEY, &data);
	if (rv >= 0)
		defsize = data.len;

	if (callbacks.get_key)   {
		rv = callbacks.get_key(profile, type, reference, defbuf, defsize, pinbuf, pinsize);
		LOG_TEST_RET(ctx, rv, "Cannot get key");
	}
	else if (rv >= 0)  {
		if (*pinsize < defsize)
			LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Get transport key error");

		memcpy(pinbuf, data.key_data, data.len);
		*pinsize = data.len;
	}

	memset(&auth_info, 0, sizeof(auth_info));
	auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
	auth_info.auth_method = type;
	auth_info.attrs.pin.reference = reference;
	auth_info.attrs.pin.stored_length = *pinsize;
	auth_info.attrs.pin.max_length = *pinsize;
	auth_info.attrs.pin.min_length = *pinsize;

	pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, "Default transport key", NULL, &auth_info);
	if (!pin_obj)
		LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate AUTH object");

	rv = sc_pkcs15_add_object(p15card, pin_obj);
	LOG_TEST_RET(ctx, rv, "Cannot add PKCS#15 AUTH object");

	sc_pkcs15_pincache_add(p15card, pin_obj, pinbuf, *pinsize);

	LOG_FUNC_RETURN(ctx, rv);
}


/*
 * PIN verification
 */
int
sc_pkcs15init_verify_secret(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
		struct sc_file *file, unsigned int type, int reference)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_pkcs15_object *pin_obj = NULL;
	struct sc_pkcs15_auth_info auth_info;
	struct sc_path	*path;
	int		r, use_pinpad = 0, pin_id = -1;
	const char	*ident, *label = NULL;
	unsigned char	pinbuf[0x100];
	size_t		pinsize = 0;


	LOG_FUNC_CALLED(ctx);
	path = file? &file->path : NULL;

	ident = get_pin_ident_name(type, reference);
	sc_log(ctx, "get and verify PIN('%s',type:0x%X,reference:0x%X)", ident, type, reference);

	if (type == SC_AC_SEN)   {
		r = sc_card_ctl(p15card->card, SC_CARDCTL_GET_CHV_REFERENCE_IN_SE, (void *)(&reference));
		sc_log(ctx, "Card CTL(GET_CHV_REFERENCE_IN_SE) returned %i", r);
		if (r > 0)   {
			sc_log(ctx, "CHV(ref:%i) found in SE(ref:%i)", r, reference);
			type = SC_AC_CHV;
			reference = r;
		}
		else if (r != SC_ERROR_NOT_SUPPORTED)
			LOG_TEST_RET(ctx, r, "Card CTL error: cannot get CHV reference");
	}

	memset(&auth_info, 0, sizeof(auth_info));
	auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
	auth_info.auth_method = type;
	auth_info.attrs.pin.reference = reference;

	pin_id = sc_pkcs15init_get_pin_reference(p15card, profile, type, reference);
	sc_log(ctx, "found PIN reference %i", pin_id);
	if (type == SC_AC_SYMBOLIC) {
		if (pin_id == -1)
			LOG_FUNC_RETURN(ctx, SC_SUCCESS);
		reference = pin_id;
		type = SC_AC_CHV;
		sc_log(ctx, "Symbolic PIN resolved to PIN(type:CHV,reference:%i)", reference);
	}

	if (path && path->len)   {
		struct sc_path tmp_path = *path;
		int iter;
		r = SC_ERROR_OBJECT_NOT_FOUND;
		for (iter = tmp_path.len/2; iter >= 0 && r == SC_ERROR_OBJECT_NOT_FOUND; iter--, tmp_path.len -= 2) {
			r = sc_pkcs15_find_pin_by_type_and_reference(p15card,
					tmp_path.len ? &tmp_path : NULL,
					type, reference, &pin_obj);
		}
	}
	else {
		r = sc_pkcs15_find_pin_by_type_and_reference(p15card, NULL, type, reference, &pin_obj);
	}

	if (!r && pin_obj)   {
		memcpy(&auth_info, pin_obj->data, sizeof(auth_info));
		sc_log(ctx, "found PIN object '%.*s'", (int) sizeof pin_obj->label, pin_obj->label);
	}

	if (pin_obj)   {
		sc_log(ctx,
		       "PIN object '%.*s'; pin_obj->content.len:%"SC_FORMAT_LEN_SIZE_T"u",
		       (int) sizeof pin_obj->label, pin_obj->label,
		       pin_obj->content.len);
		if (pin_obj->content.value && pin_obj->content.len)   {
			if (pin_obj->content.len > sizeof(pinbuf))
				LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "PIN buffer is too small");
			memcpy(pinbuf, pin_obj->content.value, pin_obj->content.len);
			pinsize = pin_obj->content.len;
			sc_log(ctx, "'ve got '%s' value from cache", ident);
			goto found;
		}
	}

	if (pin_obj && pin_obj->label[0])
		label = pin_obj->label;

	switch (type) {
	case SC_AC_CHV:
		if (callbacks.get_pin)   {
			pinsize = sizeof(pinbuf);
			r = callbacks.get_pin(profile, pin_id, &auth_info, label, pinbuf, &pinsize);
			sc_log(ctx,
			       "'get_pin' callback returned %i; pinsize:%"SC_FORMAT_LEN_SIZE_T"u",
			       r, pinsize);
		}
		break;
	case SC_AC_SCB:
	case SC_AC_PRO:
		pinsize = 0;
		r = 0;
		break;
	default:
		pinsize = sizeof(pinbuf);
		r = sc_pkcs15init_get_transport_key(profile, p15card, type, reference, pinbuf, &pinsize);
		break;
	}

	if (r == SC_ERROR_OBJECT_NOT_FOUND)   {
		if (p15card->card->reader->capabilities & SC_READER_CAP_PIN_PAD)
			r = 0, use_pinpad = 1;
		else
			r = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
	}

	LOG_TEST_RET(ctx, r, "Failed to get secret");
	if (type == SC_AC_PRO)   {
		sc_log(ctx, "No 'verify' for secure messaging");
		LOG_FUNC_RETURN(ctx, r);
	}

found:
	if (pin_obj)   {
		r = sc_pkcs15_verify_pin(p15card, pin_obj, use_pinpad || pinsize == 0 ? NULL : pinbuf, use_pinpad ? 0 : pinsize);
		LOG_TEST_RET(ctx, r, "Cannot validate pkcs15 PIN");
	}

	if (file)   {
		r = sc_select_file(p15card->card, &file->path, NULL);
		LOG_TEST_RET(ctx, r, "Failed to select PIN path");
	}

	if (!pin_obj) {
		struct sc_pin_cmd_data pin_cmd;

		memset(&pin_cmd, 0, sizeof(pin_cmd));
		pin_cmd.cmd = SC_PIN_CMD_VERIFY;
		pin_cmd.pin_type = type;
		pin_cmd.pin_reference = reference;
		pin_cmd.pin1.data = use_pinpad ? NULL : pinbuf;
		pin_cmd.pin1.len = use_pinpad ? 0: pinsize;

		r = sc_pin_cmd(p15card->card, &pin_cmd, NULL);
		LOG_TEST_RET(ctx, r, "'VERIFY' pin cmd failed");
	}

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Present any authentication info as required by the file.
 *
 * Depending on the SC_CARD_CAP_USE_FCI_AC caps file in sc_card_t,
 * we read the ACs of the file on the card, or rely on the ACL
 * info for that file in the profile file.
 *
 * In the latter case, there's a problem here if e.g. the SO PIN
 * defined by the profile is optional, and hasn't been set.
 * On the other hands, some cards do not return access conditions
 * in their response to SELECT FILE), so the latter case has been
 * used in most cards while the first case was added much later.
 */
int
sc_pkcs15init_authenticate(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
		struct sc_file *file, int op)
{
	struct sc_context *ctx = p15card->card->ctx;
	const struct sc_acl_entry *acl = NULL;
	struct sc_file *file_tmp = NULL;
	int  r = 0;

	LOG_FUNC_CALLED(ctx);
	assert(file != NULL);
	sc_log(ctx, "path '%s', op=%u", sc_print_path(&file->path), op);

	if (p15card->card->caps & SC_CARD_CAP_USE_FCI_AC) {
		r = sc_select_file(p15card->card, &file->path, &file_tmp);
		LOG_TEST_RET(ctx, r, "Authentication failed: cannot select file.");

		acl = sc_file_get_acl_entry(file_tmp, op);
	}
	else   {
		acl = sc_file_get_acl_entry(file, op);
	}
	sc_log(ctx, "acl %p",acl);

	for (; r == 0 && acl; acl = acl->next) {
		if (acl->method == SC_AC_NEVER)   {
			LOG_TEST_RET(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Authentication failed: never allowed");
		}
		else if (acl->method == SC_AC_NONE)   {
			sc_log(ctx, "always allowed");
			break;
		}
		else if (acl->method == SC_AC_UNKNOWN)  {
			sc_log(ctx, "unknown acl method");
			break;
		}
		sc_log(ctx, "verify acl(method:%i,reference:%i)", acl->method, acl->key_ref);
		r = sc_pkcs15init_verify_secret(profile, p15card, file_tmp ? file_tmp : file, acl->method, acl->key_ref);
	}

	sc_file_free(file_tmp);

	LOG_FUNC_RETURN(ctx, r);
}


static int
do_select_parent(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
		struct sc_file *file, struct sc_file **parent)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_path	path;
	int		r;

	LOG_FUNC_CALLED(ctx);
	/* Get the parent's path */
	path = file->path;
	if (path.len >= 2)
		path.len -= 2;
	if (!path.len && !path.aid.len)
		sc_format_path("3F00", &path);

	/* Select the parent DF. */
	*parent = NULL;
	r = sc_select_file(p15card->card, &path, parent);
	/* If DF doesn't exist, create it (unless it's the MF,
	 * but then something's badly broken anyway :-) */
	if (r == SC_ERROR_FILE_NOT_FOUND && path.len != 2) {
		r = sc_profile_get_file_by_path(profile, &path, parent);
		if (r < 0) {
			sc_log(ctx, "no profile template for DF %s", sc_print_path(&path));
			LOG_FUNC_RETURN(ctx, r);
		}

		r = sc_pkcs15init_create_file(profile, p15card, *parent);
		LOG_TEST_RET(ctx, r, "Cannot create parent DF");

		r = sc_select_file(p15card->card, &path, NULL);
		LOG_TEST_RET(ctx, r, "Cannot select parent DF");
	}
	else if (r == SC_SUCCESS && !strcmp(p15card->card->name, "STARCOS")) {
		/* in case of starcos spk 2.3 SELECT FILE does not
		 * give us the ACLs => ask the profile */
		sc_file_free(*parent);

		r = sc_profile_get_file_by_path(profile, &path, parent);
		if (r < 0) {
			sc_log(ctx, "in StarCOS profile there is no template for DF %s", sc_print_path(&path));
			LOG_FUNC_RETURN(ctx, r);
		}
	}
	LOG_FUNC_RETURN(ctx, r);
}


int
sc_pkcs15init_create_file(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
		struct sc_file *file)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file	*parent = NULL;
	int		r;

	LOG_FUNC_CALLED(ctx);
	if (!file) {
		return SC_ERROR_INVALID_ARGUMENTS;
	}

	sc_log(ctx, "create file '%s'", sc_print_path(&file->path));
	/* Select parent DF and verify PINs/key as necessary */
	r = do_select_parent(profile, p15card, file, &parent);
	LOG_TEST_RET(ctx, r, "Cannot create file: select parent error");

	r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_CREATE);
	LOG_TEST_RET(ctx, r, "Cannot create file: 'CREATE' authentication failed");

	/* Fix up the file's ACLs */
	r = sc_pkcs15init_fixup_file(profile, p15card, file);
	LOG_TEST_RET(ctx, r, "Cannot create file: file fixup failed");

	/* ensure we are in the correct lifecycle */
	r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
	if (r != SC_ERROR_NOT_SUPPORTED)
		LOG_TEST_RET(ctx, r, "Cannot create file: failed to set lifecycle 'ADMIN'");

	r = sc_create_file(p15card->card, file);
	LOG_TEST_RET(ctx, r, "Create file failed");

	sc_file_free(parent);
	LOG_FUNC_RETURN(ctx, r);
}


int
sc_pkcs15init_update_file(struct sc_profile *profile,
		struct sc_pkcs15_card *p15card, struct sc_file *file,
		void *data, unsigned int datalen)
{
	struct sc_context *ctx = p15card->card->ctx;
	struct sc_file	*selected_file = NULL;
	void		*copy = NULL;
	int		r, need_to_zap = 0;

	LOG_FUNC_CALLED(ctx);
	if (!file)
		LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);

	sc_log(ctx, "path:%s; datalen:%i", sc_print_path(&file->path), datalen);

	r = sc_select_file(p15card->card, &file->path, &selected_file);
	if (!r)   {
		need_to_zap = 1;
	}
	else if (r == SC_ERROR_FILE_NOT_FOUND)   {
		/* Create file if it doesn't exist */
		if (file->size < datalen)
			file->size = datalen;

		r = sc_pkcs15init_create_file(profile, p15card, file);
		LOG_TEST_RET(ctx, r, "Failed to create file");

		r = sc_select_file(p15card->card, &file->path, &selected_file);
		LOG_TEST_RET(ctx, r, "Failed to select newly created file");
	}
	else   {
		LOG_TEST_RET(ctx, r, "Failed to select file");
	}

	if (selected_file->size < datalen) {
		sc_log(ctx,
		       "File %s too small (require %u, have %"SC_FORMAT_LEN_SIZE_T"u)",
		       sc_print_path(&file->path), datalen,
		       selected_file->size);
		sc_file_free(selected_file);
		LOG_TEST_RET(ctx, SC_ERROR_FILE_TOO_SMALL, "Update file failed");
	}
	else if (selected_file->size > datalen && need_to_zap) {
		/* zero out the rest of the file - we may have shrunk
		 * the file contents */
		copy = calloc(1, selected_file->size);
		if (copy == NULL) {
			sc_file_free(selected_file);
			return SC_ERROR_OUT_OF_MEMORY;
		}
		memcpy(copy, data, datalen);
		datalen = selected_file->size;
		data = copy;
	}

	/* Present authentication info needed */
	r = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_UPDATE);
	if (r >= 0 && datalen)
		r = sc_update_binary(p15card->card, 0, (const unsigned char *) data, datalen, 0);

	if (copy)
		free(copy);
	sc_file_free(selected_file);
	LOG_FUNC_RETURN(ctx, r);
}

/*
 * Fix up a file's ACLs by replacing all occurrences of a symbolic
 * PIN name with the real reference.
 */
static int
sc_pkcs15init_fixup_acls(struct sc_pkcs15_card *p15card, struct sc_file *file,
		struct sc_acl_entry *so_acl, struct sc_acl_entry *user_acl)
{
	struct sc_context *ctx = p15card->card->ctx;
	unsigned int	op;
	int		r = 0;

	LOG_FUNC_CALLED(ctx);
	for (op = 0; r == 0 && op < SC_MAX_AC_OPS; op++) {
		struct sc_acl_entry acls[SC_MAX_OP_ACS];
		const struct sc_acl_entry *acl;
		const char	*what;
		int		added = 0, num, ii;

		/* First, get original ACLs */
		acl = sc_file_get_acl_entry(file, op);
		for (num = 0; num < SC_MAX_OP_ACS && acl; num++, acl = acl->next)
			acls[num] = *acl;

		sc_file_clear_acl_entries(file, op);
		for (ii = 0; ii < num; ii++) {
			acl = acls + ii;
			if (acl->method != SC_AC_SYMBOLIC)
				goto next;

			if (acl->key_ref == SC_PKCS15INIT_SO_PIN) {
				acl = so_acl;
				what = "SO PIN";
			}
			else if (acl->key_ref == SC_PKCS15INIT_USER_PIN) {
				acl = user_acl;
				what = "user PIN";
			}
			else {
				sc_log(ctx, "ACL references unknown symbolic PIN %d", acl->key_ref);
				return SC_ERROR_INVALID_ARGUMENTS;
			}

			/* If we weren't given a replacement ACL,
			 * leave the original ACL untouched */
			if (acl->key_ref == (unsigned int)-1) {
				sc_log(ctx, "ACL references %s, which is not defined", what);
				return SC_ERROR_INVALID_ARGUMENTS;
			}

			if (acl->method == SC_AC_NONE)
				continue;
		next:
			sc_file_add_acl_entry(file, op, acl->method, acl->key_ref);
			added++;
		}
		if (!added)
			sc_file_add_acl_entry(file, op, SC_AC_NONE, 0);
	}

	LOG_FUNC_RETURN(ctx, r);
}


/*
 * Fix up all file ACLs
 */
int
sc_pkcs15init_fixup_file(struct sc_profile *profile,
		struct sc_pkcs15_card *p15card, struct sc_file *file)
{
	struct sc_context	*ctx = profile->card->ctx;
	struct sc_acl_entry	so_acl, user_acl;
	unsigned int	op, needfix = 0;
	int		rv, pin_ref;

	LOG_FUNC_CALLED(ctx);
	/* First, loop over all ACLs to find out whether there
	 * are still any symbolic references.
	 */
	for (op = 0; op < SC_MAX_AC_OPS; op++) {
		const struct sc_acl_entry *acl;

		acl = sc_file_get_acl_entry(file, op);
		for (; acl; acl = acl->next)
			if (acl->method == SC_AC_SYMBOLIC)
				needfix++;
	}

	if (!needfix)
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);

	pin_ref = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC, SC_PKCS15INIT_SO_PIN);
	if (pin_ref < 0) {
		so_acl.method = SC_AC_NONE;
		so_acl.key_ref = 0;
	}
	else {
		so_acl.method = SC_AC_CHV;
		so_acl.key_ref = pin_ref;
	}

	pin_ref = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC, SC_PKCS15INIT_USER_PIN);
	if (pin_ref < 0) {
		user_acl.method = SC_AC_NONE;
		user_acl.key_ref = 0;
	}
	else {
		user_acl.method = SC_AC_CHV;
		user_acl.key_ref = pin_ref;
	}
	sc_log(ctx, "so_acl(method:%X,ref:%X), user_acl(method:%X,ref:%X)",
			so_acl.method, so_acl.key_ref, user_acl.method, user_acl.key_ref);

	rv = sc_pkcs15init_fixup_acls(p15card, file, &so_acl, &user_acl);

	LOG_FUNC_RETURN(ctx, rv);
}


static int
sc_pkcs15init_get_pin_path(struct sc_pkcs15_card *p15card,
		struct sc_pkcs15_id *auth_id, struct sc_path *path)
{
	struct sc_pkcs15_object *obj;
	int	r;

	r = sc_pkcs15_find_pin_by_auth_id(p15card, auth_id, &obj);
	if (r < 0)
		return r;
	*path = ((struct sc_pkcs15_auth_info *) obj->data)->path;
	return SC_SUCCESS;
}


int
sc_pkcs15init_get_pin_info(struct sc_profile *profile, int id, struct sc_pkcs15_auth_info *pin)
{
	sc_profile_get_pin_info(profile, id, pin);
	return SC_SUCCESS;
}


int
sc_pkcs15init_get_manufacturer(struct sc_profile *profile, const char **res)
{
	*res = profile->p15_spec->tokeninfo->manufacturer_id;
	return SC_SUCCESS;
}

int
sc_pkcs15init_get_serial(struct sc_profile *profile, const char **res)
{
	*res = profile->p15_spec->tokeninfo->serial_number;
	return SC_SUCCESS;
}


int
sc_pkcs15init_set_serial(struct sc_profile *profile, const char *serial)
{
	if (profile->p15_spec->tokeninfo->serial_number)
		free(profile->p15_spec->tokeninfo->serial_number);
	profile->p15_spec->tokeninfo->serial_number = strdup(serial);

	return SC_SUCCESS;
}


/*
 * Card specific sanity check procedure.
 */
int
sc_pkcs15init_sanity_check(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
{
	struct sc_context *ctx = p15card->card->ctx;
	int rv = SC_ERROR_NOT_SUPPORTED;

	LOG_FUNC_CALLED(ctx);
	if (profile->ops->sanity_check)
		rv = profile->ops->sanity_check(profile, p15card);

	LOG_FUNC_RETURN(ctx, rv);
}


static int
sc_pkcs15init_qualify_pin(struct sc_card *card, const char *pin_name,
		unsigned int pin_len, struct sc_pkcs15_auth_info *auth_info)
{
	struct sc_context *ctx = card->ctx;
	struct sc_pkcs15_pin_attributes *pin_attrs;

	LOG_FUNC_CALLED(ctx);
	if (pin_len == 0 || auth_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
		LOG_FUNC_RETURN(ctx, SC_SUCCESS);

	pin_attrs = &auth_info->attrs.pin;

	if (pin_len < pin_attrs->min_length) {
		sc_log(ctx,
		       "%s too short (min length %"SC_FORMAT_LEN_SIZE_T"u)",
		       pin_name, pin_attrs->min_length);
		LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_LENGTH);
	}
	if (pin_len > pin_attrs->max_length) {
		sc_log(ctx,
		       "%s too long (max length %"SC_FORMAT_LEN_SIZE_T"u)",
		       pin_name, pin_attrs->max_length);
		LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_LENGTH);
	}

	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}


/*
 * Get the list of options from the card, if it specifies them
 */
static int
sc_pkcs15init_read_info(struct sc_card *card, struct sc_profile *profile)
{
	struct sc_path	path;
	struct sc_file	*file = NULL;
	unsigned char	*mem = NULL;
	size_t		len = 0;
	int		r;

	sc_format_path(OPENSC_INFO_FILEPATH, &path);
	r = sc_select_file(card, &path, &file);
	if (r >= 0) {
		len = file->size;
		sc_file_free(file);
		mem = malloc(len);
		if (mem != NULL)
			r = sc_read_binary(card, 0, mem, len, 0);
		else
			r = SC_ERROR_OUT_OF_MEMORY;
	}
	else   {
		r = 0;
	}

	if (r >= 0)
		r = sc_pkcs15init_parse_info(card, mem, r, profile);

	if (mem)
		free(mem);
	return r;
}


static int
set_info_string(char **strp, const u8 *p, size_t len)
{
	char	*s;

	if (!(s = malloc(len+1)))
		return SC_ERROR_OUT_OF_MEMORY;
	memcpy(s, p, len);
	s[len] = '\0';
	if (*strp)
		free(*strp);
	*strp = s;
	return SC_SUCCESS;
}

/*
 * Parse OpenSC Info file. We rudely clobber any information
 * given on the command line.
 *
 * passed is a pointer (p) to (len) bytes. Those bytes contain
 * one or several tag-length-value constructs, where tag and
 * length are both single bytes. a final 0x00 or 0xff byte
 * (with or without len byte) is ok.
 */
static int
sc_pkcs15init_parse_info(struct sc_card *card,
		const unsigned char *p, size_t len, struct sc_profile *profile)
{
	unsigned char	tag;
	const unsigned char *end;
	unsigned int	nopts = 0;
	size_t		n;

	if ((p == NULL) || (len == 0))
		return 0;

	end = p + (len - 1);
	while (p < end) {	/* more bytes to look at */
		int	r = 0;

		tag = *p; p++;
		if ((tag == 0) || (tag == 0xff) || (p >= end))
			break;

		n = *p;
		p++;

		if (p >= end || p + n > end) /* invalid length byte n */
			goto error;

		switch (tag) {
		case OPENSC_INFO_TAG_PROFILE:
			r = set_info_string(&profile->name, p, n);
			if (r < 0)
				return r;
			break;
		case OPENSC_INFO_TAG_OPTION:
			if (nopts >= SC_PKCS15INIT_MAX_OPTIONS - 1) {
				sc_log(card->ctx, "Too many options in OpenSC Info file");
				return SC_ERROR_PKCS15INIT;
			}
			r = set_info_string(&profile->options[nopts], p, n);
			if (r < 0)
				return r;
			profile->options[++nopts] = NULL;
			break;
		default:
			/* Unknown options ignored */ ;
		}
		p += n;
	}
	return 0;

error:
	sc_log(card->ctx, "OpenSC info file corrupted");
	return SC_ERROR_PKCS15INIT;
}


static int
do_encode_string(unsigned char **memp, unsigned char *end,
		unsigned char tag, const char *s)
{
	unsigned char	*p = *memp;
	int	n;

	n = s? strlen(s) : 0;
	if (n > 255)
		return SC_ERROR_BUFFER_TOO_SMALL;
	if (p + 2 + n > end)
		return SC_ERROR_BUFFER_TOO_SMALL;
	*p++ = tag;
	*p++ = n;
	memcpy(p, s, n);
	*memp = p + n;
	return 0;
}


static int
sc_pkcs15init_write_info(struct sc_pkcs15_card *p15card,
		struct sc_profile *profile,
		struct sc_pkcs15_object *pin_obj)
{
	struct sc_file	*file = NULL, *df = profile->df_info->file;
	unsigned char	buffer[128], *p, *end;
	unsigned int	method;
	unsigned long	key_ref;
	int		n, r;

	if (profile->ops->emu_write_info)
		return profile->ops->emu_write_info(profile, p15card, pin_obj);

	memset(buffer, 0, sizeof(buffer));

	file = sc_file_new();
	file->path.type = SC_PATH_TYPE_PATH;
	memcpy(file->path.value, df->path.value, df->path.len);
	file->path.len = df->path.len;
	sc_append_file_id(&file->path, OPENSC_INFO_FILEID);
	file->type = SC_FILE_TYPE_WORKING_EF;
	file->ef_structure = SC_FILE_EF_TRANSPARENT;
	file->id = OPENSC_INFO_FILEID;
	file->size = sizeof(buffer);

	if (pin_obj != NULL) {
		method = SC_AC_CHV;
		key_ref = ((struct sc_pkcs15_auth_info *) pin_obj->data)->attrs.pin.reference;
	}
	else {
		method = SC_AC_NONE; /* Unprotected */
		key_ref = 0;
	}
	for (n = 0; n < SC_MAX_AC_OPS; n++) {
		if (n == SC_AC_OP_READ)
			sc_file_add_acl_entry(file, n, SC_AC_NONE, 0);
		else
			sc_file_add_acl_entry(file, n, method, key_ref);
	}

	p = buffer;
	end = buffer + sizeof(buffer);

	r = do_encode_string(&p, end, OPENSC_INFO_TAG_PROFILE, profile->name);
	for (n = 0; r >= 0 && profile->options[n]; n++)
		r = do_encode_string(&p, end, OPENSC_INFO_TAG_OPTION, profile->options[n]);

	if (r >= 0)
		r = sc_pkcs15init_update_file(profile, p15card, file, buffer, file->size);

	sc_file_free(file);
	return r;
}