summaryrefslogtreecommitdiff
path: root/gck/gck-session.c
blob: 031d749fdaf45d9b24c28bf61bd5ad8c0256a7ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
/* gck-session.h - the GObject PKCS#11 wrapper library

   Copyright (C) 2008, Stefan Walter

   The Gnome Keyring Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   The Gnome Keyring 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with the Gnome Library; see the file COPYING.LIB.  If not,
   see <http://www.gnu.org/licenses/>.

   Author: Stef Walter <nielsen@memberwebs.com>
*/

#include "config.h"

#include "gck.h"
#include "gck-private.h"

#include "gck/gck-marshal.h"

#include <string.h>

#include <glib/gi18n-lib.h>

/**
 * GckSession:
 *
 * Represents an open PKCS11 session.
 *
 * Before performing any PKCS11 operations, a session must be opened. This is
 * analogous to an open database handle, or a file handle.
 */

/**
 * GckSessionOptions:
 * @GCK_SESSION_READ_ONLY: Open session as read only
 * @GCK_SESSION_READ_WRITE: Open sessions as read/write
 * @GCK_SESSION_LOGIN_USER: Login as user on new sessions
 * @GCK_SESSION_AUTHENTICATE: Authenticate as necessary
 *
 * Options for creating sessions.
 */

/**
 * GckMechanism:
 * @type: The mechanism type
 * @parameter: Mechanism specific data.
 * @n_parameter: Length of mechanism specific data.
 *
 * Represents a mechanism used with crypto operations.
 */

enum {
	DISCARD_HANDLE,
	LAST_SIGNAL
};

enum {
	PROP_0,
	PROP_MODULE,
	PROP_HANDLE,
	PROP_INTERACTION,
	PROP_SLOT,
	PROP_OPTIONS,
	PROP_OPENING_FLAGS,
	PROP_APP_DATA
};

typedef struct {
	/* Not modified after construct/init */
	GckSlot *slot;
	CK_SESSION_HANDLE handle;
	GckSessionOptions options;
	gulong opening_flags;
	gpointer app_data;

	/* Changable data locked by mutex */
	GMutex mutex;
	GTlsInteraction *interaction;
	gboolean discarded;
} GckSessionPrivate;

static void    gck_session_initable_iface        (GInitableIface *iface);

static void    gck_session_async_initable_iface  (GAsyncInitableIface *iface);

G_DEFINE_TYPE_WITH_CODE (GckSession, gck_session, G_TYPE_OBJECT,
                         G_ADD_PRIVATE (GckSession);
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, gck_session_initable_iface);
                         G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, gck_session_async_initable_iface);
);

static guint signals[LAST_SIGNAL] = { 0 };

/* ----------------------------------------------------------------------------
 * OBJECT
 */

static gboolean
gck_session_real_discard_handle (GckSession *self, CK_OBJECT_HANDLE handle)
{
	CK_FUNCTION_LIST_PTR funcs;
	GckModule *module;
	CK_RV rv;

	/* The default functionality, close the handle */

	module = gck_session_get_module (self);
	g_return_val_if_fail (module != NULL, FALSE);

	funcs = gck_module_get_functions (module);
	g_return_val_if_fail (funcs, FALSE);

	rv = (funcs->C_CloseSession) (handle);
	if (rv != CKR_OK) {
		g_warning ("couldn't close session properly: %s",
		           gck_message_from_rv (rv));
	}

	g_object_unref (module);
	return TRUE;
}

static void
gck_session_init (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	g_mutex_init (&priv->mutex);
}

static void
gck_session_get_property (GObject *obj, guint prop_id, GValue *value,
                           GParamSpec *pspec)
{
	GckSession *self = GCK_SESSION (obj);

	switch (prop_id) {
	case PROP_MODULE:
		g_value_take_object (value, gck_session_get_module (self));
		break;
	case PROP_HANDLE:
		g_value_set_ulong (value, gck_session_get_handle (self));
		break;
	case PROP_SLOT:
		g_value_take_object (value, gck_session_get_slot (self));
		break;
	case PROP_OPTIONS:
		g_value_set_uint (value, gck_session_get_options (self));
		break;
	case PROP_INTERACTION:
		g_value_take_object (value, gck_session_get_interaction (self));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
		break;
	}
}

static void
gck_session_set_property (GObject *obj, guint prop_id, const GValue *value,
                           GParamSpec *pspec)
{
	GckSession *self = GCK_SESSION (obj);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	/* Only valid calls are from constructor */

	switch (prop_id) {
	case PROP_HANDLE:
		g_return_if_fail (!priv->handle);
		priv->handle = g_value_get_ulong (value);
		break;
	case PROP_INTERACTION:
		gck_session_set_interaction (self, g_value_get_object (value));
		break;
	case PROP_SLOT:
		g_return_if_fail (!priv->slot);
		priv->slot = g_value_dup_object (value);
		g_return_if_fail (priv->slot);
		break;
	case PROP_OPTIONS:
		g_return_if_fail (!priv->options);
		priv->options = g_value_get_flags (value);
		break;
	case PROP_OPENING_FLAGS:
		priv->opening_flags = g_value_get_ulong (value);
		break;
	case PROP_APP_DATA:
		priv->app_data = g_value_get_pointer (value);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
		break;
	}
}

static void
gck_session_constructed (GObject *obj)
{
	GckSession *self = GCK_SESSION (obj);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	G_OBJECT_CLASS (gck_session_parent_class)->constructed (obj);

	priv->opening_flags |= CKF_SERIAL_SESSION;
	if (priv->options & GCK_SESSION_READ_WRITE)
		priv->opening_flags |= CKF_RW_SESSION;
}

static void
gck_session_dispose (GObject *obj)
{
	GckSession *self = GCK_SESSION (obj);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	gboolean discard = FALSE;
	gboolean handled;

	g_return_if_fail (GCK_IS_SESSION (self));

	if (priv->handle != 0) {
		g_mutex_lock (&priv->mutex);
			discard = !priv->discarded;
			priv->discarded = TRUE;
		g_mutex_unlock (&priv->mutex);
	}

	if (discard) {
		/*
		 * Let the world know that we're discarding the session
		 * handle. This allows any necessary session reuse to work.
		 */

		g_signal_emit_by_name (self, "discard-handle", priv->handle, &handled);
		g_return_if_fail (handled);
	}

	G_OBJECT_CLASS (gck_session_parent_class)->dispose (obj);
}

static void
gck_session_finalize (GObject *obj)
{
	GckSession *self = GCK_SESSION (obj);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_assert (priv->handle == 0 || priv->discarded);

	g_clear_object (&priv->interaction);
	g_clear_object (&priv->slot);

	g_mutex_clear (&priv->mutex);

	G_OBJECT_CLASS (gck_session_parent_class)->finalize (obj);
}

static void
gck_session_class_init (GckSessionClass *klass)
{
	GObjectClass *gobject_class = (GObjectClass*)klass;
	gck_session_parent_class = g_type_class_peek_parent (klass);

	gobject_class->constructed = gck_session_constructed;
	gobject_class->get_property = gck_session_get_property;
	gobject_class->set_property = gck_session_set_property;
	gobject_class->dispose = gck_session_dispose;
	gobject_class->finalize = gck_session_finalize;

	klass->discard_handle = gck_session_real_discard_handle;

	/**
	 * GckSession:module:
	 *
	 * The GckModule that this session is opened on.
	 */
	g_object_class_install_property (gobject_class, PROP_MODULE,
		g_param_spec_object ("module", "Module", "PKCS11 Module",
		                     GCK_TYPE_MODULE,
		                     G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession:handle:
	 *
	 * The raw CK_SESSION_HANDLE handle of this session.
	 */
	g_object_class_install_property (gobject_class, PROP_HANDLE,
		g_param_spec_ulong ("handle", "Session Handle", "PKCS11 Session Handle",
		                    0, G_MAXULONG, 0,
		                    G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession:slot:
	 *
	 * The GckSlot this session is opened on.
	 */
	g_object_class_install_property (gobject_class, PROP_SLOT,
		g_param_spec_object ("slot", "Slot that this session uses", "PKCS11 Slot",
		                     GCK_TYPE_SLOT,
		                     G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession:options:
	 *
	 * The options this session was opened with.
	 */
	g_object_class_install_property (gobject_class, PROP_OPTIONS,
		g_param_spec_flags ("options", "Session Options", "Session Options",
		                    GCK_TYPE_SESSION_OPTIONS, GCK_SESSION_READ_ONLY,
		                    G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession:interaction:
	 *
	 * Interaction object used to ask the user for pins when opening
	 * sessions. Used if the session_options of the enumerator have
	 * %GCK_SESSION_LOGIN_USER
	 */
	g_object_class_install_property (gobject_class, PROP_INTERACTION,
		g_param_spec_object ("interaction", "Interaction", "Interaction asking for pins",
		                     G_TYPE_TLS_INTERACTION,
		                     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession:opening-flags:
	 *
	 * Raw PKCS#11 flags used to open the PKCS#11 session.
	 */
	g_object_class_install_property (gobject_class, PROP_OPENING_FLAGS,
		g_param_spec_ulong ("opening-flags", "Opening flags", "PKCS#11 open session flags",
		                    0, G_MAXULONG, 0,
		                    G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession:app-data:
	 *
	 * Raw PKCS#11 application data used to open the PKCS#11 session.
	 */
	g_object_class_install_property (gobject_class, PROP_APP_DATA,
		g_param_spec_pointer ("app-data", "App data", "PKCS#11 application data",
		                      G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

	/**
	 * GckSession::discard-handle:
	 * @session: The session.
	 * @handle: The handle being discarded.
	 *
	 * When a GckSession is being disposed of it emits this signal to allow
	 * a session pool to pick up the handle and keep it around.
	 *
	 * If no signal handler claims the handle, then it is closed.
	 *
	 * Returns: Whether or not this handle was claimed.
	 */
	signals[DISCARD_HANDLE] = g_signal_new ("discard-handle", GCK_TYPE_SESSION,
	                G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GckSessionClass, discard_handle),
			g_signal_accumulator_true_handled, NULL,
			_gck_marshal_BOOLEAN__ULONG, G_TYPE_BOOLEAN, 1, G_TYPE_ULONG);
}

typedef struct OpenSession {
	GckArguments base;
	GTlsInteraction *interaction;
	GckSlot *slot;
	gulong flags;
	gpointer app_data;
	CK_NOTIFY notify;
	gboolean auto_login;
	CK_SESSION_HANDLE session;
} OpenSession;

static void
free_open_session (OpenSession *args)
{
	g_clear_object (&args->interaction);
	g_clear_object (&args->slot);
	g_free (args);
}

static CK_RV
perform_open_session (OpenSession *args)
{
	CK_RV rv = CKR_OK;

	/* First step, open session */
	if (!args->session) {
		rv = (args->base.pkcs11->C_OpenSession) (args->base.handle, args->flags,
		                                         args->app_data, args->notify, &args->session);
	}

	if (rv != CKR_OK || !args->auto_login)
		return rv;

	rv = _gck_session_authenticate_token (args->base.pkcs11, args->session,
	                                      args->slot, args->interaction, NULL);

	return rv;
}

static gboolean
gck_session_initable_init (GInitable *initable,
                           GCancellable *cancellable,
                           GError **error)
{
	GckSession *self = GCK_SESSION (initable);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	OpenSession args = { GCK_ARGUMENTS_INIT, 0,  };
	GckModule *module = NULL;
	gboolean ret = FALSE;
	gboolean want_login;

	want_login = (priv->options & GCK_SESSION_LOGIN_USER) == GCK_SESSION_LOGIN_USER;

	/* Already have a session setup? */
	if (priv->handle && !want_login)
		return TRUE;

	g_object_ref (self);
	module = gck_session_get_module (self);

	/* Open a new session */
	args.slot = priv->slot;
	args.app_data = priv->app_data;
	args.notify = NULL;
	args.session = priv->handle;
	args.flags = priv->opening_flags;
	args.interaction = priv->interaction ? g_object_ref (priv->interaction) : NULL;
	args.auto_login = want_login;

	if (_gck_call_sync (priv->slot, perform_open_session, NULL, &args, cancellable, error)) {
		priv->handle = args.session;
		ret = TRUE;
	}

	g_clear_object (&args.interaction);
	g_object_unref (module);
	g_object_unref (self);

	return ret;
}

static void
gck_session_initable_iface (GInitableIface *iface)
{
	iface->init = gck_session_initable_init;
}

static void
gck_session_initable_init_async (GAsyncInitable *initable,
                                 int io_priority,
                                 GCancellable *cancellable,
                                 GAsyncReadyCallback callback,
                                 gpointer user_data)
{
	GckSession *self = GCK_SESSION (initable);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	OpenSession *args;
	gboolean want_login;
	GckCall *call;

	g_object_ref (self);

	call =  _gck_call_async_prep (priv->slot, perform_open_session, NULL,
	                              sizeof (*args), free_open_session);

	args = _gck_call_get_arguments (call);
	want_login = (priv->options & GCK_SESSION_LOGIN_USER) == GCK_SESSION_LOGIN_USER;
	args->session = priv->handle;

	_gck_call_async_ready (call, self, cancellable, callback, user_data);

	/* Already have a session setup? */
	if (priv->handle && !want_login) {
		_gck_call_async_short (call, CKR_OK);
		g_object_unref (self);
		return;
	}

	args->app_data = priv->app_data;
	args->notify = NULL;
	args->slot = g_object_ref (priv->slot);
	args->interaction = priv->interaction ? g_object_ref (priv->interaction) : NULL;
	args->auto_login = want_login;
	args->flags = priv->opening_flags;

	_gck_call_async_go (call);
	g_object_unref (self);
}

static gboolean
gck_session_initable_init_finish (GAsyncInitable *initable,
                                  GAsyncResult *result,
                                  GError **error)
{
	GckSession *self = GCK_SESSION (initable);
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	gboolean ret = FALSE;

	g_object_ref (self);

	{
		OpenSession *args;

		if (_gck_call_basic_finish (result, error)) {
			args = _gck_call_async_result_arguments (result, OpenSession);
			priv->handle = args->session;
			ret = TRUE;
		}
	}

	g_object_unref (self);

	return ret;
}

static void
gck_session_async_initable_iface (GAsyncInitableIface *iface)
{
	iface->init_async = gck_session_initable_init_async;
	iface->init_finish = gck_session_initable_init_finish;
}

/* ----------------------------------------------------------------------------
 * PUBLIC
 */

/**
 * GckSessionInfo:
 * @slot_id: The handle of the PKCS11 slot that this session is opened on.
 * @state: The user login state of the session.
 * @flags: Various PKCS11 flags.
 * @device_error: The last device error that occurred from an operation on this session.
 *
 * Information about the session. This is analogous to a CK_SESSION_INFO structure.
 *
 * When done with this structure, release it using gck_session_info_free().
 */

G_DEFINE_BOXED_TYPE (GckSessionInfo, gck_session_info,
                     gck_session_info_copy, gck_session_info_free)

/**
 * gck_session_info_copy:
 * @session_info: a session info structure
 *
 * Make a new copy of a session info structure.
 *
 * Returns: (transfer full): a new copy of the session info
 */
GckSessionInfo *
gck_session_info_copy (GckSessionInfo *session_info)
{
	return g_memdup2 (session_info, sizeof (GckSessionInfo));
}

/**
 * gck_session_info_free:
 * @session_info: Session info to free.
 *
 * Free the GckSessionInfo structure and all associated memory.
 **/
void
gck_session_info_free (GckSessionInfo *session_info)
{
	if (!session_info)
		return;
	g_free (session_info);
}

/**
 * gck_session_from_handle:
 * @slot: The slot which the session belongs to.
 * @session_handle: the raw PKCS#11 handle of the session
 * @options: Session options. Those which are used during opening a session have no effect.
 *
 * Initialize a session object from a raw PKCS#11 session handle.
 * Usually one would use the [method@Slot.open_session] function to
 * create a session.
 *
 * Returns: (transfer full): the new GckSession object
 **/
GckSession *
gck_session_from_handle (GckSlot *slot,
                         gulong session_handle,
                         GckSessionOptions options)
{
	GckSession *session;

	g_return_val_if_fail (GCK_IS_SLOT (slot), NULL);

	session = g_object_new (GCK_TYPE_SESSION,
	                        "handle", session_handle,
	                        "slot", slot,
	                        "options", options,
	                        NULL);

	return session;
}

/**
 * gck_session_get_handle:
 * @self: The session object.
 *
 * Get the raw PKCS#11 session handle from a session object.
 *
 * Return value: The raw session handle.
 **/
gulong
gck_session_get_handle (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_return_val_if_fail (GCK_IS_SESSION (self), (CK_SESSION_HANDLE)-1);

	return priv->handle;
}

/**
 * gck_session_get_module:
 * @self: The session object.
 *
 * Get the PKCS#11 module to which this session belongs.
 *
 * Returns: (transfer full): the module, which should be unreffed after use
 **/
GckModule *
gck_session_get_module (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);

	return gck_slot_get_module (priv->slot);
}

/**
 * gck_session_get_slot:
 * @self: The session object.
 *
 * Get the PKCS#11 slot to which this session belongs.
 *
 * Return value: (transfer full): The slot, which should be unreffed after use.
 **/
GckSlot *
gck_session_get_slot (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (GCK_IS_SLOT (priv->slot), NULL);

	return g_object_ref (priv->slot);
}

/**
 * gck_session_get_info:
 * @self: The session object.
 *
 * Get information about the session.
 *
 * Returns: (transfer full): the session info. Use the gck_session_info_free()
 *          to release when done
 **/
GckSessionInfo*
gck_session_get_info (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	GckSessionInfo *sessioninfo;
	CK_FUNCTION_LIST_PTR funcs;
	CK_SESSION_INFO info;
	GckModule *module;
	CK_RV rv;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);

	module = gck_session_get_module (self);
	g_return_val_if_fail (GCK_IS_MODULE (module), NULL);

	funcs = gck_module_get_functions (module);
	g_return_val_if_fail (funcs, NULL);

	memset (&info, 0, sizeof (info));
	rv = (funcs->C_GetSessionInfo) (priv->handle, &info);

	g_object_unref (module);

	if (rv != CKR_OK) {
		g_warning ("couldn't get session info: %s", gck_message_from_rv (rv));
		return NULL;
	}

	sessioninfo = g_new0 (GckSessionInfo, 1);
	sessioninfo->flags = info.flags;
	sessioninfo->slot_id = info.slotID;
	sessioninfo->state = info.state;
	sessioninfo->device_error = info.ulDeviceError;

	return sessioninfo;
}

/**
 * gck_session_get_state:
 * @self: the session
 *
 * Get the session state. The state is the various PKCS#11 CKS_XXX flags.
 *
 * Returns: the session state
 */
gulong
gck_session_get_state (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	CK_FUNCTION_LIST_PTR funcs;
	CK_SESSION_INFO info;
	GckModule *module;
	CK_RV rv;

	g_return_val_if_fail (GCK_IS_SESSION (self), 0);

	module = gck_session_get_module (self);
	g_return_val_if_fail (GCK_IS_MODULE (module), 0);

	funcs = gck_module_get_functions (module);
	g_return_val_if_fail (funcs, 0);

	memset (&info, 0, sizeof (info));
	rv = (funcs->C_GetSessionInfo) (priv->handle, &info);

	g_object_unref (module);

	if (rv != CKR_OK) {
		g_warning ("couldn't get session info: %s", gck_message_from_rv (rv));
		return 0;
	}

	return info.state;
}

/**
 * gck_session_get_options:
 * @self: The session to get options from.
 *
 * Get the options this session was opened with.
 *
 * Return value: The session options.
 **/
GckSessionOptions
gck_session_get_options (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_return_val_if_fail (GCK_IS_SESSION (self), 0);

	return priv->options;
}

/**
 * gck_session_get_interaction:
 * @self: the session
 *
 * Get the interaction object set on this session, which is used to prompt
 * for pins and the like.
 *
 * Returns: (transfer full) (nullable): the interaction object, or %NULL
 */
GTlsInteraction *
gck_session_get_interaction (GckSession *self)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);

	if (priv->interaction)
		return g_object_ref (priv->interaction);

	return NULL;
}

/**
 * gck_session_set_interaction:
 * @self: the session
 * @interaction: (nullable): the interaction or %NULL
 *
 * Set the interaction object on this session, which is used to prompt for
 * pins and the like.
 */
void
gck_session_set_interaction (GckSession *self,
                             GTlsInteraction *interaction)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (interaction == NULL || G_IS_TLS_INTERACTION (interaction));

	g_mutex_lock (&priv->mutex);
	g_set_object (&priv->interaction, interaction);
	g_mutex_unlock (&priv->mutex);
}

/**
 * gck_session_open:
 * @slot: the slot to open session on
 * @options: session options
 * @interaction: (nullable): optional interaction for logins or object authentication
 * @cancellable: (nullable): optional cancellation object
 * @error: location to place error or %NULL
 *
 * Open a session on the slot. This call may block for an indefinite period.
 *
 * Returns: (transfer full): the new session
 */
GckSession *
gck_session_open (GckSlot *slot,
                  GckSessionOptions options,
                  GTlsInteraction *interaction,
                  GCancellable *cancellable,
                  GError **error)
{
	return g_initable_new (GCK_TYPE_SESSION, cancellable, error,
	                       "slot", slot,
	                       "interaction", interaction,
	                       "options", options,
	                       NULL);
}

/**
 * gck_session_open_async:
 * @slot: the slot to open session on
 * @options: session options
 * @interaction: (nullable): optional interaction for logins or object authentication
 * @cancellable: optional cancellation object
 * @callback: called when the operation completes
 * @user_data: data to pass to callback
 *
 * Open a session on the slot. This call will return immediately and complete
 * asynchronously.
 */
void
gck_session_open_async (GckSlot *slot,
                        GckSessionOptions options,
                        GTlsInteraction *interaction,
                        GCancellable *cancellable,
                        GAsyncReadyCallback callback,
                        gpointer user_data)
{
	g_async_initable_new_async (GCK_TYPE_SESSION, G_PRIORITY_DEFAULT,
	                            cancellable, callback, user_data,
	                            "slot", slot,
	                            "interaction", interaction,
	                            "options", options,
	                            NULL);
}

/**
 * gck_session_open_finish:
 * @result: the result passed to the callback
 * @error: location to return an error or %NULL
 *
 * Get the result of an open session operation.
 *
 * Returns: (transfer full): the new session
 */
GckSession *
gck_session_open_finish (GAsyncResult *result,
                         GError **error)
{
	GObject *ret;
	GObject *source;

	source = g_async_result_get_source_object (result);
	ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source), result, error);
	g_object_unref (source);

	return ret ? GCK_SESSION (ret) : NULL;
}

/* ---------------------------------------------------------------------------------------------
 * INIT PIN
 */

typedef struct _InitPin {
	GckArguments base;
	guchar *pin;
	gsize n_pin;
} InitPin;


static void
free_init_pin (InitPin *args)
{
	g_free (args->pin);
	g_free (args);
}

static CK_RV
perform_init_pin (InitPin *args)
{
	return (args->base.pkcs11->C_InitPIN) (args->base.handle, (CK_BYTE_PTR)args->pin,
	                                       args->n_pin);
}

/**
 * gck_session_init_pin:
 * @self: Initialize PIN for this session's slot.
 * @pin: (nullable) (array length=n_pin): the user's PIN, or %NULL for
 *       protected authentication path
 * @n_pin: the length of the PIN
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error.
 *
 * Initialize the user's pin on this slot that this session is opened on.
 * According to the PKCS#11 standards, the session must be logged in with
 * the CKU_SO user type.
 *
 * This call may block for an indefinite period.
 *
 * Return value: Whether successful or not.
 **/
gboolean
gck_session_init_pin (GckSession *self, const guchar *pin, gsize n_pin,
                      GCancellable *cancellable, GError **error)
{
	InitPin args = { GCK_ARGUMENTS_INIT, (guchar*)pin, n_pin };
	return _gck_call_sync (self, perform_init_pin, NULL, &args, cancellable, error);

}

/**
 * gck_session_init_pin_async:
 * @self: Initialize PIN for this session's slot.
 * @pin: (nullable) (array length=n_pin): the user's PIN, or %NULL for protected authentication path
 * @n_pin: the length of the PIN
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Initialize the user's pin on this slot that this session is opened on.
 * According to the PKCS#11 standards, the session must be logged in with
 * the `CKU_SO` user type.
 *
 * This call will return immediately and completes asynchronously.
 **/
void
gck_session_init_pin_async (GckSession *self, const guchar *pin, gsize n_pin,
                             GCancellable *cancellable, GAsyncReadyCallback callback,
                             gpointer user_data)
{
	GckCall *call;
	InitPin* args;

	call = _gck_call_async_prep (self, perform_init_pin, NULL, sizeof (*args), free_init_pin);
	args = _gck_call_get_arguments (call);

	args->pin = pin && n_pin ? g_memdup2 (pin, n_pin) : NULL;
	args->n_pin = n_pin;

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_init_pin_finish:
 * @self: The session.
 * @result: The result passed to the callback.
 * @error: A location to return an error.
 *
 * Get the result of initializing a user's PIN.
 *
 * Return value: Whether the operation was successful or not.
 **/
gboolean
gck_session_init_pin_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	return _gck_call_basic_finish (result, error);
}


/* ---------------------------------------------------------------------------------------------
 * SET PIN
 */

typedef struct _SetPin {
	GckArguments base;
	guchar *old_pin;
	gsize n_old_pin;
	guchar *new_pin;
	gsize n_new_pin;
} SetPin;

static void
free_set_pin (SetPin *args)
{
	g_free (args->old_pin);
	g_free (args->new_pin);
	g_free (args);
}

static CK_RV
perform_set_pin (SetPin *args)
{
	return (args->base.pkcs11->C_SetPIN) (args->base.handle, (CK_BYTE_PTR)args->old_pin,
	                                      args->n_old_pin, args->new_pin, args->n_new_pin);
}

/**
 * gck_session_set_pin:
 * @self: Change the PIN for this session's slot.
 * @old_pin: (nullable) (array length=n_old_pin): the user's old PIN, or %NULL
 *           for protected authentication path.
 * @n_old_pin: The length of the PIN.
 * @new_pin: (nullable) (array length=n_new_pin): the user's new PIN, or %NULL
 *           for protected authentication path
 * @n_new_pin: The length of the PIN.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error.
 *
 * Change the user's pin on this slot that this session is opened on.
 *
 * This call may block for an indefinite period.
 *
 * Return value: Whether successful or not.
 **/
gboolean
gck_session_set_pin (GckSession *self, const guchar *old_pin, gsize n_old_pin,
                     const guchar *new_pin, gsize n_new_pin, GCancellable *cancellable,
                     GError **error)
{
	SetPin args = { GCK_ARGUMENTS_INIT, (guchar*)old_pin, n_old_pin, (guchar*)new_pin, n_new_pin };
	return _gck_call_sync (self, perform_set_pin, NULL, &args, cancellable, error);
}

/**
 * gck_session_set_pin_async:
 * @self: Change the PIN for this session's slot.
 * @old_pin: (nullable) (array length=n_new_pin): the user's old PIN, or %NULL
 *           for protected authentication path
 * @n_old_pin: the length of the old PIN
 * @new_pin: (nullable) (array length=n_new_pin): the user's new PIN, or %NULL
 *           for protected authentication path
 * @n_new_pin: the length of the new PIN
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Change the user's pin on this slot that this session is opened on.
 *
 * This call will return immediately and completes asynchronously.
 **/
void
gck_session_set_pin_async (GckSession *self, const guchar *old_pin, gsize n_old_pin,
                            const guchar *new_pin, gsize n_new_pin, GCancellable *cancellable,
                            GAsyncReadyCallback callback, gpointer user_data)
{
	SetPin* args;
	GckCall *call;

	call = _gck_call_async_prep (self, perform_set_pin, NULL, sizeof (*args), free_set_pin);
	args = _gck_call_get_arguments (call);

	args->old_pin = old_pin && n_old_pin ? g_memdup2 (old_pin, n_old_pin) : NULL;
	args->n_old_pin = n_old_pin;
	args->new_pin = new_pin && n_new_pin ? g_memdup2 (new_pin, n_new_pin) : NULL;
	args->n_new_pin = n_new_pin;

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_set_pin_finish:
 * @self: The session.
 * @result: The result passed to the callback.
 * @error: A location to return an error.
 *
 * Get the result of changing a user's PIN.
 *
 * Return value: Whether the operation was successful or not.
 **/
gboolean
gck_session_set_pin_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	return _gck_call_basic_finish (result, error);
}


/* ---------------------------------------------------------------------------------------------
 * LOGIN
 */

typedef struct _Login {
	GckArguments base;
	gulong user_type;
	guchar *pin;
	gsize n_pin;
} Login;

static void
free_login (Login *args)
{
	g_free (args->pin);
	g_free (args);
}

static CK_RV
perform_login (Login *args)
{
	return (args->base.pkcs11->C_Login) (args->base.handle, args->user_type,
	                                     (CK_BYTE_PTR)args->pin, args->n_pin);
}

/**
 * gck_session_login:
 * @self: Log in to this session.
 * @user_type: The type of login user.
 * @pin: (nullable) (array length=n_pin): the user's PIN, or %NULL for
 *       protected authentication path
 * @n_pin: The length of the PIN.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error.
 *
 * Login the user on the session. This call may block for
 * an indefinite period.
 *
 * Return value: Whether successful or not.
 **/
gboolean
gck_session_login (GckSession *self, gulong user_type, const guchar *pin,
                   gsize n_pin, GCancellable *cancellable, GError **error)
{
	Login args = { GCK_ARGUMENTS_INIT, user_type, (guchar*)pin, n_pin };
	return _gck_call_sync (self, perform_login, NULL, &args, cancellable, error);

}

/**
 * gck_session_login_async:
 * @self: Log in to this session.
 * @user_type: The type of login user.
 * @pin: (nullable) (array length=n_pin): the user's PIN, or %NULL for
 *       protected authentication path
 * @n_pin: The length of the PIN.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Login the user on the session. This call will return
 * immediately and completes asynchronously.
 **/
void
gck_session_login_async (GckSession *self, gulong user_type, const guchar *pin,
                          gsize n_pin, GCancellable *cancellable, GAsyncReadyCallback callback,
                          gpointer user_data)
{
	Login* args;
	GckCall *call;

	call = _gck_call_async_prep (self, perform_login, NULL, sizeof (*args), free_login);
	args = _gck_call_get_arguments (call);

	args->user_type = user_type;
	args->pin = pin && n_pin ? g_memdup2 (pin, n_pin) : NULL;
	args->n_pin = n_pin;

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_login_finish:
 * @self: The session logged into.
 * @result: The result passed to the callback.
 * @error: A location to return an error.
 *
 * Get the result of a login operation.
 *
 * Return value: Whether the operation was successful or not.
 **/
gboolean
gck_session_login_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	return _gck_call_basic_finish (result, error);
}

typedef struct _Interactive {
	GckArguments base;
	GTlsInteraction *interaction;
	GCancellable *cancellable;
	GckSlot *token;
} Interactive;

static void
free_interactive (Interactive *args)
{
	g_clear_object (&args->token);
	g_clear_object (&args->cancellable);
	g_clear_object (&args->interaction);
	g_free (args);
}

static CK_RV
perform_interactive (Interactive *args)
{
	return _gck_session_authenticate_token (args->base.pkcs11, args->base.handle,
	                                        args->token, args->interaction, args->cancellable);
}

/**
 * gck_session_login_interactive:
 * @self: session to use for login
 * @user_type: the type of login user
 * @interaction: (nullable): interaction to request PIN when necessary
 * @cancellable: (nullable): optional cancellation object, or %NULL
 * @error: location to return an error
 *
 * Login the user on the session requesting the password interactively
 * when necessary. This call may block for an indefinite period.
 *
 * Return value: Whether successful or not.
 */
gboolean
gck_session_login_interactive (GckSession *self,
                               gulong user_type,
                               GTlsInteraction *interaction,
                               GCancellable *cancellable,
                               GError **error)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	Interactive args = { GCK_ARGUMENTS_INIT, interaction, cancellable, NULL, };

	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);
	g_return_val_if_fail (interaction == NULL || G_IS_TLS_INTERACTION (interaction), FALSE);
	g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

	/* TODO: For now this is all we support */
	g_return_val_if_fail (user_type == CKU_USER, FALSE);

	args.token = priv->slot;

	return _gck_call_sync (self, perform_interactive, NULL, &args, cancellable, error);
}

/**
 * gck_session_login_interactive_async:
 * @self: session to use for login
 * @user_type: the type of login user
 * @interaction: (nullable): interaction to request PIN when necessary
 * @cancellable: (nullable): optional cancellation object, or %NULL
 * @callback: called when the operation completes
 * @user_data: data to pass to the callback
 *
 * Login the user on the session prompting for passwords interactively when
 * necessary. This call will return immediately and completes asynchronously.
 **/
void
gck_session_login_interactive_async (GckSession *self,
                                     gulong user_type,
                                     GTlsInteraction *interaction,
                                     GCancellable *cancellable,
                                     GAsyncReadyCallback callback,
                                     gpointer user_data)
{
	GckSessionPrivate *priv = gck_session_get_instance_private (self);
	Interactive* args;
	GckCall *call;

	call = _gck_call_async_prep (self, perform_interactive, NULL, sizeof (*args), free_interactive);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (interaction == NULL || G_IS_TLS_INTERACTION (interaction));
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

	/* TODO: For now this is all we support */
	g_return_if_fail (user_type == CKU_USER);

	args->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
	args->interaction = interaction ? g_object_ref (interaction) : NULL;
	args->token = g_object_ref (priv->slot);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_login_interactive_finish:
 * @self: the session logged into
 * @result: the result passed to the callback
 * @error: location to return an error
 *
 * Get the result of a login operation.
 *
 * Return value: Whether the operation was successful or not.
 **/
gboolean
gck_session_login_interactive_finish (GckSession *self,
                                      GAsyncResult *result,
                                      GError **error)
{
	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);

	return _gck_call_basic_finish (result, error);
}

/* LOGOUT */

static CK_RV
perform_logout (GckArguments *args)
{
	return (args->pkcs11->C_Logout) (args->handle);
}

/**
 * gck_session_logout:
 * @self: Logout of this session.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error.
 *
 * Log out of the session. This call may block for an indefinite period.
 *
 * Return value: Whether the logout was successful or not.
 **/
gboolean
gck_session_logout (GckSession *self, GCancellable *cancellable, GError **error)
{
	GckArguments args = GCK_ARGUMENTS_INIT;
	return _gck_call_sync (self, perform_logout, NULL, &args, cancellable, error);
}

/**
 * gck_session_logout_async:
 * @self: Logout of this session.
 * @cancellable: Optional cancellation object, or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Log out of the session. This call returns immediately and completes
 * asynchronously.
 **/
void
gck_session_logout_async (GckSession *self, GCancellable *cancellable,
                           GAsyncReadyCallback callback, gpointer user_data)
{
	GckCall *call;

	call = _gck_call_async_prep (self, perform_logout, NULL, 0, NULL);
	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_logout_finish:
 * @self: Logout of this session.
 * @result: The result passed to the callback.
 * @error: A location to return an error.
 *
 * Get the result of logging out of a session.
 *
 * Return value: Whether the logout was successful or not.
 **/
gboolean
gck_session_logout_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	return _gck_call_basic_finish (result, error);
}


/* CREATE OBJECT */

typedef struct _CreateObject {
	GckArguments base;
	GckAttributes *attrs;
	CK_OBJECT_HANDLE object;
} CreateObject;

static void
free_create_object (CreateObject *args)
{
	gck_attributes_unref (args->attrs);
	g_free (args);
}

static CK_RV
perform_create_object (CreateObject *args)
{
	CK_ATTRIBUTE_PTR attrs;
	CK_ULONG n_attrs;
	CK_RV rv;

	attrs = _gck_attributes_commit_out (args->attrs, &n_attrs);

	rv = (args->base.pkcs11->C_CreateObject) (args->base.handle,
	                                          attrs, n_attrs,
	                                          &args->object);

	gchar *string = gck_attributes_to_string (args->attrs);
	if (rv == CKR_OK)
		g_debug ("created object: %s", string);
	else
		g_debug ("failed %s to create object: %s",
		         _gck_stringize_rv (rv), string);
	g_free (string);

	return rv;
}

/**
 * gck_session_create_object:
 * @self: The session to create the object on.
 * @attrs: The attributes to create the object with.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Create a new PKCS#11 object. This call may block for an
 * indefinite period.
 *
 * Returns: (transfer full): the newly created object or %NULL if an error occurred
 **/
GckObject *
gck_session_create_object (GckSession *self, GckAttributes *attrs,
                           GCancellable *cancellable, GError **error)
{
	CreateObject args = { GCK_ARGUMENTS_INIT, attrs, 0 };
	gboolean ret;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (attrs != NULL, NULL);

	ret = _gck_call_sync (self, perform_create_object, NULL, &args, cancellable, error);

	if (!ret)
		return NULL;

	return gck_object_from_handle (self, args.object);
}

/**
 * gck_session_create_object_async:
 * @self: The session to create the object on.
 * @attrs: The attributes to create the object with.
 * @cancellable: (nullable): Optional cancellation object or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Create a new PKCS#11 object. This call will return immediately
 * and complete asynchronously.
 *
 * If @attrs is a floating reference, it is consumed.
 **/
void
gck_session_create_object_async (GckSession *self, GckAttributes *attrs,
                                  GCancellable *cancellable, GAsyncReadyCallback callback,
                                  gpointer user_data)
{
	GckCall *call;
	CreateObject *args;

	call = _gck_call_async_prep (self, perform_create_object,
	                              NULL, sizeof (*args), free_create_object);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (attrs);

	args->attrs = gck_attributes_ref (attrs);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_create_object_finish:
 * @self: The session to create the object on.
 * @result: The result passed to the callback.
 * @error: A location to return an error, or %NULL.
 *
 * Get the result of creating a new PKCS#11 object.
 *
 * Return value: (transfer full): the newly created object or %NULL if an error occurred
 **/
GckObject *
gck_session_create_object_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	CreateObject *args;

	args = _gck_call_async_result_arguments (result, CreateObject);

	if (!_gck_call_basic_finish (result, error))
		return NULL;
	return gck_object_from_handle (self, args->object);
}


/* FIND OBJECTS */

typedef struct _FindObjects {
	GckArguments base;
	GckAttributes *attrs;
	CK_OBJECT_HANDLE_PTR objects;
	CK_ULONG n_objects;
} FindObjects;

static void
free_find_objects (FindObjects *args)
{
	gck_attributes_unref (args->attrs);
	g_free (args->objects);
	g_free (args);
}

static CK_RV
perform_find_objects (FindObjects *args)
{
	CK_OBJECT_HANDLE_PTR batch;
	CK_ULONG n_batch, n_found;
	CK_ATTRIBUTE_PTR attrs;
	CK_ULONG n_attrs;
	GArray *array;
	CK_RV rv;

	gchar *string = gck_attributes_to_string (args->attrs);
	g_debug ("matching: %s", string);
	g_free (string);

	attrs = _gck_attributes_commit_out (args->attrs, &n_attrs);

	rv = (args->base.pkcs11->C_FindObjectsInit) (args->base.handle,
	                                             attrs, n_attrs);
	if (rv != CKR_OK)
		return rv;

	batch = NULL;
	n_found = n_batch = 4;
	array = g_array_new (0, 1, sizeof (CK_OBJECT_HANDLE));

	do {
		/*
		 * Reallocate and double in size:
		 *  - First time.
		 *  - Each time we found as many as batch
		 */

		if (n_found == n_batch) {
			n_batch *= 2;
			batch = g_realloc (batch, sizeof (CK_OBJECT_HANDLE) * n_batch);
		}

		rv = (args->base.pkcs11->C_FindObjects) (args->base.handle,
		                                         batch, n_batch, &n_found);
		if (rv != CKR_OK)
			break;

		g_array_append_vals (array, batch, n_found);

	} while (n_found > 0);

	g_free (batch);

	if (rv == CKR_OK) {
		args->n_objects = array->len;
		args->objects = (CK_OBJECT_HANDLE_PTR)g_array_free (array, FALSE);
		rv = (args->base.pkcs11->C_FindObjectsFinal) (args->base.handle);
	} else {
		args->objects = NULL;
		args->n_objects = 0;
		g_array_free (array, TRUE);
	}

	return rv;
}

/**
 * gck_session_find_handles:
 * @self: the session to find objects on
 * @match: the attributes to match against objects
 * @cancellable: (nullable): optional cancellation object or %NULL
 * @n_handles: location to return number of handles
 * @error: a location to return an error or %NULL
 *
 * Find the objects matching the passed attributes. This call may
 * block for an indefinite period.
 *
 * Returns: (transfer full) (array length=n_handles) (nullable): a list of
 *          the matching objects, which may be empty
 **/
gulong *
gck_session_find_handles (GckSession *self,
                          GckAttributes *match,
                          GCancellable *cancellable,
                          gulong *n_handles,
                          GError **error)
{
	FindObjects args = { GCK_ARGUMENTS_INIT, match, NULL, 0 };
	gulong *results = NULL;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (match != NULL, NULL);
	g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
	g_return_val_if_fail (n_handles != NULL, NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

	if (_gck_call_sync (self, perform_find_objects, NULL, &args, cancellable, error)) {
		results = args.objects;
		*n_handles = args.n_objects;
		args.objects = NULL;
	}

	g_free (args.objects);
	return results;
}

/**
 * gck_session_find_handles_async:
 * @self: the session to find objects on
 * @match: the attributes to match against the objects
 * @cancellable: (nullable): optional cancellation object or %NULL
 * @callback: called when the operation completes
 * @user_data: data to pass to the callback
 *
 * Find the objects matching the passed attributes. This call will
 * return immediately and complete asynchronously.
 *
 * If @match is a floating reference, it is consumed.
 **/
void
gck_session_find_handles_async (GckSession *self,
                                GckAttributes *match,
                                GCancellable *cancellable,
                                GAsyncReadyCallback callback,
                                gpointer user_data)
{
	GckCall *call;
	FindObjects *args;

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (match != NULL);
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

	call = _gck_call_async_prep (self, perform_find_objects,
	                             NULL, sizeof (*args), free_find_objects);
	args = _gck_call_get_arguments (call);
	args->attrs = gck_attributes_ref (match);
	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_find_handles_finish:
 * @self: the session
 * @result: the asynchronous result
 * @n_handles: location to store number of handles returned
 * @error: a location to return an error on failure
 *
 * Get the result of a find handles operation.
 *
 * Returns: (transfer full) (array length=n_handles) (nullable): an array of
 *          handles that matched, which may be empty, or %NULL on failure
 **/
gulong *
gck_session_find_handles_finish (GckSession *self,
                                 GAsyncResult *result,
                                 gulong *n_handles,
                                 GError **error)
{
	gulong *results = NULL;
	FindObjects *args;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (n_handles != NULL, NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

	args = _gck_call_async_result_arguments (result, FindObjects);

	if (!_gck_call_basic_finish (result, error))
		return NULL;
	*n_handles = args->n_objects;
	results = args->objects;
	args->objects = NULL;
	return results;
}

/**
 * gck_session_find_objects:
 * @self: The session to find objects on.
 * @match: the attributes to match
 * @cancellable: (nullable): Optional cancellation object or %NULL.
 * @error: A location to return an error or %NULL.
 *
 * Find the objects matching the passed attributes. This call may
 * block for an indefinite period.
 *
 * If @match is a floating reference, it is consumed.
 *
 * Returns: (transfer full) (element-type Gck.Object): a list of the matching
 *          objects, which may be empty
 **/
GList *
gck_session_find_objects (GckSession *self,
                          GckAttributes *match,
                          GCancellable *cancellable,
                          GError **error)
{
	GList *results = NULL;
	gulong *handles;
	gulong n_handles;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (match != NULL, NULL);
	g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

	handles = gck_session_find_handles (self, match, cancellable, &n_handles, error);
	if (handles == NULL)
		return NULL;

	results = gck_objects_from_handle_array (self, handles, n_handles);
	g_free (handles);
	return results;
}

/**
 * gck_session_find_objects_async:
 * @self: The session to find objects on.
 * @match: The attributes to match.
 * @cancellable: (nullable): Optional cancellation object or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Find the objects matching the passed attributes. This call will
 * return immediately and complete asynchronously.
 *
 * If the @match #GckAttributes is floating, it is consumed.
 **/
void
gck_session_find_objects_async (GckSession *self,
                                GckAttributes *match,
                                GCancellable *cancellable,
                                GAsyncReadyCallback callback,
                                gpointer user_data)
{
	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (match != NULL);
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

	gck_session_find_handles_async (self, match, cancellable, callback, user_data);
}

/**
 * gck_session_find_objects_finish:
 * @self: The session to find objects on.
 * @result: The attributes to match.
 * @error: A location to return an error.
 *
 * Get the result of a find operation.
 *
 * Returns: (transfer full) (element-type Gck.Object): a list of the matching
 *          objects, which may be empty
 **/
GList *
gck_session_find_objects_finish (GckSession *self,
                                 GAsyncResult *result,
                                 GError **error)
{
	GList *results = NULL;
	gulong *handles;
	gulong n_handles;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

	handles = gck_session_find_handles_finish (self, result, &n_handles, error);
	if (handles == NULL)
		return NULL;

	results = gck_objects_from_handle_array (self, handles, n_handles);
	g_free (handles);
	return results;

}

/**
 * gck_session_enumerate_objects:
 * @self: session to enumerate objects on
 * @match: attributes that the objects must match, or empty for all objects
 *
 * Setup an enumerator for listing matching objects available via this session.
 *
 * This call will not block but will return an enumerator immediately.
 *
 * Returns: (transfer full): a new enumerator
 **/
GckEnumerator *
gck_session_enumerate_objects (GckSession *session,
                               GckAttributes *match)
{
	GckUriData *uri_data;

	g_return_val_if_fail (match != NULL, NULL);

	uri_data = gck_uri_data_new ();
	uri_data->attributes = gck_attributes_ref (match);

	return _gck_enumerator_new_for_session (session, uri_data);
}

/* -----------------------------------------------------------------------------
 * KEY PAIR GENERATION
 */

typedef struct _GenerateKeyPair {
	GckArguments base;
	GckMechanism mechanism;
	GckAttributes *public_attrs;
	GckAttributes *private_attrs;
	CK_OBJECT_HANDLE public_key;
	CK_OBJECT_HANDLE private_key;
} GenerateKeyPair;

static void
free_generate_key_pair (GenerateKeyPair *args)
{
	g_clear_pointer (&args->public_attrs, gck_attributes_unref);
	g_clear_pointer (&args->private_attrs, gck_attributes_unref);
	g_free (args);
}

static CK_RV
perform_generate_key_pair (GenerateKeyPair *args)
{
	CK_ATTRIBUTE_PTR pub_attrs, priv_attrs;
	CK_ULONG n_pub_attrs, n_priv_attrs;

	g_assert (sizeof (CK_MECHANISM) == sizeof (GckMechanism));

	pub_attrs = _gck_attributes_commit_out (args->public_attrs, &n_pub_attrs);
	priv_attrs = _gck_attributes_commit_out (args->private_attrs, &n_priv_attrs);

	return (args->base.pkcs11->C_GenerateKeyPair) (args->base.handle,
	                                               (CK_MECHANISM_PTR)&(args->mechanism),
	                                               pub_attrs, n_pub_attrs,
	                                               priv_attrs, n_priv_attrs,
	                                               &args->public_key,
	                                               &args->private_key);
}

/**
 * gck_session_generate_key_pair:
 * @self: The session to use.
 * @mech_type: The mechanism type to use for key generation.
 * @public_attrs: Additional attributes for the generated public key.
 * @private_attrs: Additional attributes for the generated private key.
 * @public_key: (optional) (out): location to return the resulting public key
 * @private_key: (optional) (out): location to return the resulting private key.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Generate a new key pair of public and private keys. This call may block for
 * an indefinite period.
 *
 * If @public_attrs and/or @private_attrs is a floating reference, it is
 * consumed.
 *
 * Return value: %TRUE if the operation succeeded.
 **/
gboolean
gck_session_generate_key_pair (GckSession *self, gulong mech_type,
                               GckAttributes *public_attrs, GckAttributes *private_attrs,
                               GckObject **public_key, GckObject **private_key,
                               GCancellable *cancellable, GError **error)
{
	GckMechanism mech = { mech_type, NULL, 0 };
	return gck_session_generate_key_pair_full (self, &mech, public_attrs, private_attrs, public_key, private_key, cancellable, error);
}

/**
 * gck_session_generate_key_pair_full:
 * @self: The session to use.
 * @mechanism: The mechanism to use for key generation.
 * @public_attrs: Additional attributes for the generated public key.
 * @private_attrs: Additional attributes for the generated private key.
 * @public_key: (optional) (out): a location to return the resulting public key
 * @private_key: (optional) (out): a location to return the resulting private key
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Generate a new key pair of public and private keys. This call may block for an
 * indefinite period.
 *
 * Return value: %TRUE if the operation succeeded.
 **/
gboolean
gck_session_generate_key_pair_full (GckSession *self,
                                    GckMechanism *mechanism,
                                    GckAttributes *public_attrs,
                                    GckAttributes *private_attrs,
                                    GckObject **public_key,
                                    GckObject **private_key,
                                    GCancellable *cancellable,
                                    GError **error)
{
	GenerateKeyPair args = { GCK_ARGUMENTS_INIT, GCK_MECHANISM_EMPTY, public_attrs, private_attrs, 0, 0 };
	gboolean ret;

	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);
	g_return_val_if_fail (mechanism, FALSE);
	g_return_val_if_fail (public_attrs, FALSE);
	g_return_val_if_fail (private_attrs, FALSE);

	/* Shallow copy of the mechanism structure */
	memcpy (&args.mechanism, mechanism, sizeof (args.mechanism));

	ret = _gck_call_sync (self, perform_generate_key_pair, NULL, &args, cancellable, error);

	if (!ret)
		return FALSE;

	if (public_key)
		*public_key = gck_object_from_handle (self, args.public_key);
	if (private_key)
		*private_key = gck_object_from_handle (self, args.private_key);
	return TRUE;
}

/**
 * gck_session_generate_key_pair_async:
 * @self: The session to use.
 * @mechanism: The mechanism to use for key generation.
 * @public_attrs: Additional attributes for the generated public key.
 * @private_attrs: Additional attributes for the generated private key.
 * @cancellable: (nullable): Optional cancellation object or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Generate a new key pair of public and private keys. This call will
 * return immediately and complete asynchronously.
 *
 * If @public_attrs and/or @private_attrs is a floating reference, it is
 * consumed.
 **/
void
gck_session_generate_key_pair_async (GckSession *self, GckMechanism *mechanism,
                                      GckAttributes *public_attrs, GckAttributes *private_attrs,
                                      GCancellable *cancellable, GAsyncReadyCallback callback,
                                      gpointer user_data)
{
	GckCall *call;
	GenerateKeyPair *args;

	call  = _gck_call_async_prep (self, perform_generate_key_pair,
	                              NULL, sizeof (*args), free_generate_key_pair);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (mechanism);
	g_return_if_fail (public_attrs);
	g_return_if_fail (private_attrs);

	/* Shallow copy of the mechanism structure */
	memcpy (&args->mechanism, mechanism, sizeof (args->mechanism));

	args->public_attrs = gck_attributes_ref (public_attrs);
	args->private_attrs = gck_attributes_ref (private_attrs);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_generate_key_pair_finish:
 * @self: The session to use.
 * @result: The async result passed to the callback.
 * @public_key: (optional) (out): a location to return the resulting public key
 * @private_key: (optional) (out): a location to return the resulting private key
 * @error: A location to return an error.
 *
 * Get the result of a generate key pair operation.
 *
 * Return value: %TRUE if the operation succeeded.
 **/
gboolean
gck_session_generate_key_pair_finish (GckSession *self,
                                      GAsyncResult *result,
                                      GckObject **public_key,
                                      GckObject **private_key,
                                      GError **error)
{
	GenerateKeyPair *args;

	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);
	g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

	args = _gck_call_async_result_arguments (result, GenerateKeyPair);

	if (!_gck_call_basic_finish (result, error))
		return FALSE;

	if (public_key)
		*public_key = gck_object_from_handle (self, args->public_key);
	if (private_key)
		*private_key = gck_object_from_handle (self, args->private_key);
	return TRUE;
}

/* -----------------------------------------------------------------------------
 * KEY WRAPPING
 */

typedef struct _WrapKey {
	GckArguments base;
	GckMechanism mechanism;
	CK_OBJECT_HANDLE wrapper;
	CK_OBJECT_HANDLE wrapped;
	gpointer result;
	gulong n_result;
} WrapKey;

static void
free_wrap_key (WrapKey *args)
{
	g_clear_pointer (&args->result, g_free);
	g_free (args);
}

static CK_RV
perform_wrap_key (WrapKey *args)
{
	CK_RV rv;

	g_assert (sizeof (CK_MECHANISM) == sizeof (GckMechanism));

	/* Get the length of the result */
	rv = (args->base.pkcs11->C_WrapKey) (args->base.handle,
	                                     (CK_MECHANISM_PTR)&(args->mechanism),
	                                     args->wrapper, args->wrapped,
	                                     NULL, &args->n_result);
	if (rv != CKR_OK)
		return rv;

	/* And try again with a real buffer */
	args->result = g_malloc0 (args->n_result);
	return (args->base.pkcs11->C_WrapKey) (args->base.handle,
	                                       (CK_MECHANISM_PTR)&(args->mechanism),
	                                       args->wrapper, args->wrapped,
	                                       args->result, &args->n_result);
}

/**
 * gck_session_wrap_key:
 * @self: The session to use.
 * @wrapper: The key to use for wrapping.
 * @mech_type: The mechanism type to use for wrapping.
 * @wrapped: The key to wrap.
 * @n_result: A location in which to return the length of the wrapped data.
 * @cancellable: (nullable): A #GCancellable or %NULL
 * @error: A location to return an error, or %NULL.
 *
 * Wrap a key into a byte stream. This call may block for an
 * indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the wrapped data or %NULL
 *          if the operation failed
 **/
guchar *
gck_session_wrap_key (GckSession *self, GckObject *key, gulong mech_type,
                      GckObject *wrapped, gsize *n_result, GCancellable *cancellable, GError **error)
{
	GckMechanism mech = { mech_type, NULL, 0 };
	return gck_session_wrap_key_full (self, key, &mech, wrapped, n_result, cancellable, error);
}

/**
 * gck_session_wrap_key_full:
 * @self: The session to use.
 * @wrapper: The key to use for wrapping.
 * @mechanism: The mechanism to use for wrapping.
 * @wrapped: The key to wrap.
 * @n_result: A location in which to return the length of the wrapped data.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Wrap a key into a byte stream. This call may block for an
 * indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the wrapped data or %NULL
 *          if the operation failed
 **/
guchar *
gck_session_wrap_key_full (GckSession *self, GckObject *wrapper, GckMechanism *mechanism,
                            GckObject *wrapped, gsize *n_result, GCancellable *cancellable,
                            GError **error)
{
	WrapKey args = { GCK_ARGUMENTS_INIT, GCK_MECHANISM_EMPTY, 0, 0, NULL, 0 };
	gboolean ret;

	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);
	g_return_val_if_fail (mechanism, FALSE);
	g_return_val_if_fail (GCK_IS_OBJECT (wrapped), FALSE);
	g_return_val_if_fail (GCK_IS_OBJECT (wrapper), FALSE);
	g_return_val_if_fail (n_result, FALSE);

	/* Shallow copy of the mechanism structure */
	memcpy (&args.mechanism, mechanism, sizeof (args.mechanism));

	g_object_get (wrapper, "handle", &args.wrapper, NULL);
	g_return_val_if_fail (args.wrapper != 0, NULL);
	g_object_get (wrapped, "handle", &args.wrapped, NULL);
	g_return_val_if_fail (args.wrapped != 0, NULL);

	ret = _gck_call_sync (self, perform_wrap_key, NULL, &args, cancellable, error);

	if (!ret)
		return FALSE;

	*n_result = args.n_result;
	return args.result;
}

/**
 * gck_session_wrap_key_async:
 * @self: The session to use.
 * @wrapper: The key to use for wrapping.
 * @mechanism: The mechanism to use for wrapping.
 * @wrapped: The key to wrap.
 * @cancellable: (nullable): Optional cancellation object or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Wrap a key into a byte stream. This call will
 * return immediately and complete asynchronously.
 **/
void
gck_session_wrap_key_async (GckSession *self, GckObject *key, GckMechanism *mechanism,
                             GckObject *wrapped, GCancellable *cancellable,
                             GAsyncReadyCallback callback, gpointer user_data)
{
	GckCall *call;
	WrapKey *args;

	call = _gck_call_async_prep (self, perform_wrap_key,
	                              NULL, sizeof (*args), free_wrap_key);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (mechanism);
	g_return_if_fail (GCK_IS_OBJECT (wrapped));
	g_return_if_fail (GCK_IS_OBJECT (key));

	/* Shallow copy of the mechanism structure */
	memcpy (&args->mechanism, mechanism, sizeof (args->mechanism));

	g_object_get (key, "handle", &args->wrapper, NULL);
	g_return_if_fail (args->wrapper != 0);
	g_object_get (wrapped, "handle", &args->wrapped, NULL);
	g_return_if_fail (args->wrapped != 0);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_wrap_key_finish:
 * @self: The session to use.
 * @result: The async result passed to the callback.
 * @n_result: A location in which to return the length of the wrapped data.
 * @error: A location to return an error.
 *
 * Get the result of a wrap key operation.
 *
 * Returns: (transfer full) (array length=n_result): the wrapped data or %NULL
 *          if the operation failed
 **/
guchar *
gck_session_wrap_key_finish (GckSession *self, GAsyncResult *result,
                              gsize *n_result, GError **error)
{
	WrapKey *args;
	gpointer ret;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);
	g_return_val_if_fail (n_result, NULL);

	args = _gck_call_async_result_arguments (result, WrapKey);

	if (!_gck_call_basic_finish (result, error))
		return NULL;

	*n_result = args->n_result;
	args->n_result = 0;
	ret = args->result;
	args->result = NULL;

	return ret;
}

/* -----------------------------------------------------------------------------
 * KEY UNWRAPPING
 */

typedef struct _UnwrapKey {
	GckArguments base;
	GckMechanism mechanism;
	GckAttributes *attrs;
	CK_OBJECT_HANDLE wrapper;
	gconstpointer input;
	gulong n_input;
	CK_OBJECT_HANDLE unwrapped;
} UnwrapKey;

static void
free_unwrap_key (UnwrapKey *args)
{
	g_clear_pointer (&args->attrs, gck_attributes_unref);
	g_free (args);
}

static CK_RV
perform_unwrap_key (UnwrapKey *args)
{
	CK_ATTRIBUTE_PTR attrs;
	CK_ULONG n_attrs;

	g_assert (sizeof (CK_MECHANISM) == sizeof (GckMechanism));

	attrs = _gck_attributes_commit_out (args->attrs, &n_attrs);

	return (args->base.pkcs11->C_UnwrapKey) (args->base.handle,
	                                         (CK_MECHANISM_PTR)&(args->mechanism),
	                                         args->wrapper, (CK_BYTE_PTR)args->input,
	                                         args->n_input, attrs, n_attrs,
	                                         &args->unwrapped);
}

/**
 * gck_session_unwrap_key:
 * @self: The session to use.
 * @wrapper: The key to use for unwrapping.
 * @mech_type: The mechanism to use for unwrapping.
 * @input: (array length=n_input): the wrapped data as a byte stream
 * @n_input: The length of the wrapped data.
 * @attrs: Additional attributes for the unwrapped key.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Unwrap a key from a byte stream. This call may block for an
 * indefinite period.
 *
 * Returns: (transfer full): the new unwrapped key or %NULL if the
 *          operation failed
 **/
GckObject *
gck_session_unwrap_key (GckSession *self,
                        GckObject *wrapper,
                        gulong mech_type,
                        const guchar *input,
                        gsize n_input,
                        GckAttributes *attrs,
                        GCancellable *cancellable,
                        GError **error)
{
	GckMechanism mech = { mech_type, NULL, 0 };
	return gck_session_unwrap_key_full (self, wrapper, &mech, input, n_input, attrs, cancellable, error);
}

/**
 * gck_session_unwrap_key_full:
 * @self: The session to use.
 * @wrapper: The key to use for unwrapping.
 * @mechanism: The mechanism to use for unwrapping.
 * @input: (array length=n_input): the wrapped data as a byte stream
 * @n_input: The length of the wrapped data.
 * @attrs: Additional attributes for the unwrapped key.
 * @cancellable: (nullable): Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Unwrap a key from a byte stream. This call may block for an
 * indefinite period.
 *
 * Returns: (transfer full): the new unwrapped key or %NULL if the operation
 *          failed
 **/
GckObject *
gck_session_unwrap_key_full (GckSession *self,
                             GckObject *wrapper,
                             GckMechanism *mechanism,
                             const guchar *input,
                             gsize n_input,
                             GckAttributes *attrs,
                             GCancellable *cancellable,
                             GError **error)
{
	UnwrapKey args = { GCK_ARGUMENTS_INIT, GCK_MECHANISM_EMPTY, attrs, 0, input, n_input, 0 };
	gboolean ret;

	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);
	g_return_val_if_fail (GCK_IS_OBJECT (wrapper), FALSE);
	g_return_val_if_fail (mechanism, FALSE);
	g_return_val_if_fail (attrs, FALSE);

	/* Shallow copy of the mechanism structure */
	memcpy (&args.mechanism, mechanism, sizeof (args.mechanism));

	g_object_get (wrapper, "handle", &args.wrapper, NULL);
	g_return_val_if_fail (args.wrapper != 0, NULL);

	ret = _gck_call_sync (self, perform_unwrap_key, NULL, &args, cancellable, error);

	if (!ret)
		return NULL;

	return gck_object_from_handle (self, args.unwrapped);
}

/**
 * gck_session_unwrap_key_async:
 * @self: The session to use.
 * @wrapper: The key to use for unwrapping.
 * @mechanism: The mechanism to use for unwrapping.
 * @input: (array length=n_input): the wrapped data as a byte stream
 * @n_input: The length of the wrapped data.
 * @attrs: Additional attributes for the unwrapped key.
 * @cancellable: (nullable): Optional cancellation object or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Unwrap a key from a byte stream. This call will
 * return immediately and complete asynchronously.
 **/
void
gck_session_unwrap_key_async (GckSession *self,
                              GckObject *wrapper,
                              GckMechanism *mechanism,
                              const guchar *input,
                              gsize n_input,
                              GckAttributes *attrs,
                              GCancellable *cancellable,
                              GAsyncReadyCallback callback,
                              gpointer user_data)
{
	GckCall *call;
	UnwrapKey *args;

	call = _gck_call_async_prep (self, perform_unwrap_key,
	                             NULL, sizeof (*args), free_unwrap_key);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (GCK_IS_OBJECT (wrapper));
	g_return_if_fail (attrs);

	g_object_get (wrapper, "handle", &args->wrapper, NULL);
	g_return_if_fail (args->wrapper != 0);

	/* Shallow copy of the mechanism structure */
	memcpy (&args->mechanism, mechanism, sizeof (args->mechanism));

	args->attrs = gck_attributes_ref (attrs);
	args->input = input;
	args->n_input = n_input;

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_unwrap_key_finish:
 * @self: The session to use.
 * @result: The async result passed to the callback.
 * @error: A location to return an error.
 *
 * Get the result of a unwrap key operation.
 *
 * Returns: (transfer full): the new unwrapped key or %NULL if the operation
 *          failed.
 **/
GckObject *
gck_session_unwrap_key_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	UnwrapKey *args;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);

	args = _gck_call_async_result_arguments (result, UnwrapKey);

	if (!_gck_call_basic_finish (result, error))
		return NULL;
	return gck_object_from_handle (self, args->unwrapped);
}

/* -----------------------------------------------------------------------------
 * KEY DERIVATION
 */

typedef struct _DeriveKey {
	GckArguments base;
	GckMechanism mechanism;
	GckAttributes *attrs;
	CK_OBJECT_HANDLE key;
	CK_OBJECT_HANDLE derived;
} DeriveKey;

static void
free_derive_key (DeriveKey *args)
{
	g_clear_pointer (&args->attrs, gck_attributes_unref);
	g_free (args);
}

static CK_RV
perform_derive_key (DeriveKey *args)
{
	CK_ATTRIBUTE_PTR attrs;
	CK_ULONG n_attrs;

	g_assert (sizeof (CK_MECHANISM) == sizeof (GckMechanism));

	attrs = _gck_attributes_commit_out (args->attrs, &n_attrs);

	return (args->base.pkcs11->C_DeriveKey) (args->base.handle,
	                                         (CK_MECHANISM_PTR)&(args->mechanism),
	                                         args->key, attrs, n_attrs,
	                                         &args->derived);
}

/**
 * gck_session_derive_key:
 * @self: The session to use.
 * @base: The key to derive from.
 * @mech_type: The mechanism to use for derivation.
 * @attrs: Additional attributes for the derived key.
 * @cancellable: Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Derive a key from another key. This call may block for an
 * indefinite period.
 *
 * If the @attrs #GckAttributes is floating, it is consumed.
 *
 * Returns: (transfer full): the new derived key or %NULL if the operation
 *          failed
 **/
GckObject *
gck_session_derive_key (GckSession *self, GckObject *base, gulong mech_type,
                        GckAttributes *attrs, GCancellable *cancellable, GError **error)
{
	GckMechanism mech = { mech_type, NULL, 0 };
	return gck_session_derive_key_full (self, base, &mech, attrs, cancellable, error);
}

/**
 * gck_session_derive_key_full:
 * @self: The session to use.
 * @base: The key to derive from.
 * @mechanism: The mechanism to use for derivation.
 * @attrs: Additional attributes for the derived key.
 * @cancellable: Optional cancellation object, or %NULL.
 * @error: A location to return an error, or %NULL.
 *
 * Derive a key from another key. This call may block for an
 * indefinite period.
 *
 * Returns: (transfer full): the new derived key or %NULL if the operation
 *          failed
 **/
GckObject*
gck_session_derive_key_full (GckSession *self, GckObject *base, GckMechanism *mechanism,
                             GckAttributes *attrs, GCancellable *cancellable, GError **error)
{
	DeriveKey args = { GCK_ARGUMENTS_INIT, GCK_MECHANISM_EMPTY, attrs, 0, 0 };
	gboolean ret;

	g_return_val_if_fail (GCK_IS_SESSION (self), FALSE);
	g_return_val_if_fail (GCK_IS_OBJECT (base), FALSE);
	g_return_val_if_fail (mechanism, FALSE);
	g_return_val_if_fail (attrs, FALSE);

	/* Shallow copy of the mechanism structure */
	memcpy (&args.mechanism, mechanism, sizeof (args.mechanism));

	g_object_get (base, "handle", &args.key, NULL);
	g_return_val_if_fail (args.key != 0, NULL);

	ret = _gck_call_sync (self, perform_derive_key, NULL, &args, cancellable, error);

	if (!ret)
		return NULL;

	return gck_object_from_handle (self, args.derived);
}

/**
 * gck_session_derive_key_async:
 * @self: The session to use.
 * @base: The key to derive from.
 * @mechanism: The mechanism to use for derivation.
 * @attrs: Additional attributes for the derived key.
 * @cancellable: Optional cancellation object or %NULL.
 * @callback: Called when the operation completes.
 * @user_data: Data to pass to the callback.
 *
 * Derive a key from another key. This call will
 * return immediately and complete asynchronously.
 **/
void
gck_session_derive_key_async (GckSession *self, GckObject *base, GckMechanism *mechanism,
                               GckAttributes *attrs, GCancellable *cancellable,
                               GAsyncReadyCallback callback, gpointer user_data)
{
	GckCall *call;
	DeriveKey *args;

	call = _gck_call_async_prep (self, perform_derive_key,
	                             NULL, sizeof (*args), free_derive_key);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_SESSION (self));
	g_return_if_fail (GCK_IS_OBJECT (base));
	g_return_if_fail (attrs);

	g_object_get (base, "handle", &args->key, NULL);
	g_return_if_fail (args->key != 0);

	/* Shallow copy of the mechanism structure */
	memcpy (&args->mechanism, mechanism, sizeof (args->mechanism));

	args->attrs = gck_attributes_ref (attrs);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_derive_key_finish:
 * @self: The session to use.
 * @result: The async result passed to the callback.
 * @error: A location to return an error.
 *
 * Get the result of a derive key operation.
 *
 * Returns: (transfer full): the new derived key or %NULL if the operation
 *          failed
 **/
GckObject *
gck_session_derive_key_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	DeriveKey *args;

	g_return_val_if_fail (GCK_IS_SESSION (self), NULL);

	args = _gck_call_async_result_arguments (result, DeriveKey);

	if (!_gck_call_basic_finish (result, error))
		return NULL;

	return gck_object_from_handle (self, args->derived);
}

/* --------------------------------------------------------------------------------------------------
 * COMMON CRYPTO ROUTINES
 */

typedef struct _Crypt {
	GckArguments base;

	/* Functions to call */
	CK_C_EncryptInit init_func;
	CK_C_Encrypt complete_func;

	/* Interaction */
	GckObject *key_object;
	GTlsInteraction *interaction;

	/* Input */
	CK_OBJECT_HANDLE key;
	GckMechanism mechanism;
	guchar *input;
	CK_ULONG n_input;

	/* Output */
	guchar *result;
	CK_ULONG n_result;

} Crypt;

static CK_RV
perform_crypt (Crypt *args)
{
	CK_RV rv;

	g_assert (args);
	g_assert (args->init_func);
	g_assert (args->complete_func);
	g_assert (!args->result);
	g_assert (!args->n_result);

	/* Initialize the crypt operation */
	rv = (args->init_func) (args->base.handle, (CK_MECHANISM_PTR)&(args->mechanism), args->key);
	if (rv != CKR_OK)
		return rv;

	rv = _gck_session_authenticate_key (args->base.pkcs11, args->base.handle,
	                                    args->key_object, args->interaction, NULL);

	if (rv != CKR_OK)
		return rv;

	/* Get the length of the result */
	rv = (args->complete_func) (args->base.handle, args->input, args->n_input, NULL, &args->n_result);
	if (rv != CKR_OK)
		return rv;

	/* And try again with a real buffer */
	args->result = g_malloc0 (args->n_result);
	return (args->complete_func) (args->base.handle, args->input, args->n_input, args->result, &args->n_result);
}

static void
free_crypt (Crypt *args)
{
	g_clear_object (&args->interaction);
	g_clear_object (&args->key_object);

	g_clear_pointer (&args->input, g_free);
	g_clear_pointer (&args->result, g_free);
	g_free (args);
}

static guchar*
crypt_sync (GckSession *self, GckObject *key, GckMechanism *mechanism, const guchar *input,
            gsize n_input, gsize *n_result, GCancellable *cancellable, GError **error,
            CK_C_EncryptInit init_func, CK_C_Encrypt complete_func)
{
	Crypt args;

	g_return_val_if_fail (GCK_IS_OBJECT (key), NULL);
	g_return_val_if_fail (mechanism, NULL);
	g_return_val_if_fail (init_func, NULL);
	g_return_val_if_fail (complete_func, NULL);

	memset (&args, 0, sizeof (args));
	g_object_get (key, "handle", &args.key, NULL);
	g_return_val_if_fail (args.key != 0, NULL);

	/* Shallow copy of the mechanism structure */
	memcpy (&args.mechanism, mechanism, sizeof (args.mechanism));

	/* No need to copy in this case */
	args.input = (guchar*)input;
	args.n_input = n_input;

	args.init_func = init_func;
	args.complete_func = complete_func;

	args.key_object = key;
	args.interaction = gck_session_get_interaction (self);

	if (!_gck_call_sync (self, perform_crypt, NULL, &args, cancellable, error)) {
		g_free (args.result);
		args.result = NULL;
	} else {
		*n_result = args.n_result;
	}

	g_clear_object (&args.interaction);
	return args.result;
}

static void
crypt_async (GckSession *self, GckObject *key, GckMechanism *mechanism, const guchar *input,
             gsize n_input, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data,
             CK_C_EncryptInit init_func, CK_C_Encrypt complete_func)
{
	GckCall *call;
	Crypt *args;

	call = _gck_call_async_prep (self, perform_crypt, NULL, sizeof (*args), free_crypt);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_OBJECT (key));
	g_return_if_fail (mechanism);
	g_return_if_fail (init_func);
	g_return_if_fail (complete_func);

	g_object_get (key, "handle", &args->key, NULL);
	g_return_if_fail (args->key != 0);

	/* Shallow copy of the mechanism structure */
	memcpy (&args->mechanism, mechanism, sizeof (args->mechanism));

	args->input = input && n_input ? g_memdup2 (input, n_input) : NULL;
	args->n_input = n_input;

	args->init_func = init_func;
	args->complete_func = complete_func;

	args->key_object = g_object_ref (key);
	args->interaction = gck_session_get_interaction (self);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

static guchar*
crypt_finish (GckSession *self, GAsyncResult *result, gsize *n_result, GError **error)
{
	Crypt *args;
	guchar *res;

	if (!_gck_call_basic_finish (result, error))
		return NULL;
	args = _gck_call_async_result_arguments (result, Crypt);

	/* Steal the values from the results */
	res = args->result;
	args->result = NULL;
	*n_result = args->n_result;
	args->n_result = 0;

	return res;
}

/* --------------------------------------------------------------------------------------------------
 * ENCRYPT
 */

/**
 * gck_session_encrypt:
 * @self: The session.
 * @key: The key to encrypt with.
 * @mech_type: The mechanism type to use for encryption.
 * @input: (array length=n_input): the data to encrypt
 * @n_input: the length of the data to encrypt
 * @n_result: location to store the length of the result data
 * @cancellable: Optional cancellation object, or %NULL
 * @error: A location to place error information.
 *
 * Encrypt data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the data that was encrypted,
 *          or %NULL if an error occured.
 */
guchar *
gck_session_encrypt (GckSession *self, GckObject *key, gulong mech_type, const guchar *input,
                      gsize n_input, gsize *n_result, GCancellable *cancellable, GError **error)
{
	GckMechanism mechanism = { mech_type, NULL, 0 };
	return gck_session_encrypt_full (self, key, &mechanism, input, n_input, n_result, cancellable, error);
}

/**
 * gck_session_encrypt_full:
 * @self: The session.
 * @key: The key to encrypt with.
 * @mechanism: The mechanism type and parameters to use for encryption.
 * @input: (array length=n_input): the data to encrypt
 * @n_input: the length of the data to encrypt
 * @n_result: location to store the length of the result data
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @error: A location to place error information.
 *
 * Encrypt data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the data that was encrypted,
 *          or %NULL if an error occured
 */
guchar *
gck_session_encrypt_full (GckSession *self, GckObject *key, GckMechanism *mechanism,
                           const guchar *input, gsize n_input, gsize *n_result,
                           GCancellable *cancellable, GError **error)
{
	GckModule *module = NULL;
	CK_FUNCTION_LIST_PTR funcs;
	guchar *ret;

	g_object_get (self, "module", &module, NULL);
	g_return_val_if_fail (module != NULL, NULL);

	funcs = gck_module_get_functions (module);
	g_return_val_if_fail (module != NULL, NULL);

	ret = crypt_sync (self, key, mechanism, input, n_input, n_result, cancellable, error,
	                  funcs->C_EncryptInit, funcs->C_Encrypt);

	g_object_unref (module);
	return ret;
}

/**
 * gck_session_encrypt_async:
 * @self: The session.
 * @key: The key to encrypt with.
 * @mechanism: The mechanism type and parameters to use for encryption.
 * @input: (array length=n_input): the data to encrypt
 * @n_input: length of the data to encrypt
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @callback: Called when the operation completes.
 * @user_data: A pointer to pass to the callback.
 *
 * Encrypt data in a mechanism specific manner. This call will
 * return immediately and complete asynchronously.
 **/
void
gck_session_encrypt_async (GckSession *self, GckObject *key, GckMechanism *mechanism,
                            const guchar *input, gsize n_input, GCancellable *cancellable,
                            GAsyncReadyCallback callback, gpointer user_data)
{
	GckModule *module = NULL;
	CK_FUNCTION_LIST_PTR funcs;

	g_object_get (self, "module", &module, NULL);
	g_return_if_fail (module != NULL);

	funcs = gck_module_get_functions (module);
	g_return_if_fail (module != NULL);

	crypt_async (self, key, mechanism, input, n_input, cancellable, callback, user_data,
	             funcs->C_EncryptInit, funcs->C_Encrypt);

	g_object_unref (module);
}

/**
 * gck_session_encrypt_finish:
 * @self: The session.
 * @result: The result object passed to the callback.
 * @n_result: A location to store the length of the result data.
 * @error: A location to place error information.
 *
 * Get the result of an encryption operation.
 *
 * Returns: (transfer full) (array length=n_result): the data that was encrypted,
 *          or %NULL if an error occurred.
 */
guchar*
gck_session_encrypt_finish (GckSession *self, GAsyncResult *result, gsize *n_result,
                             GError **error)
{
	return crypt_finish (self, result, n_result, error);
}

/* --------------------------------------------------------------------------------------------------
 * DECRYPT
 */

/**
 * gck_session_decrypt:
 * @self: The session.
 * @key: The key to decrypt with.
 * @mech_type: The mechanism type to use for decryption.
 * @input: (array length=n_input): data to decrypt
 * @n_input: length of the data to decrypt
 * @n_result: location to store the length of the result data
 * @cancellable: Optional cancellation object, or %NULL
 * @error: A location to place an error.
 *
 * Decrypt data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the data that was decrypted,
 *          or %NULL if an error occured
 */
guchar *
gck_session_decrypt (GckSession *self, GckObject *key, gulong mech_type, const guchar *input,
                      gsize n_input, gsize *n_result, GCancellable *cancellable, GError **error)
{
	GckMechanism mechanism = { mech_type, NULL, 0 };
	return gck_session_decrypt_full (self, key, &mechanism, input, n_input, n_result, cancellable, error);
}

/**
 * gck_session_decrypt_full:
 * @self: The session.
 * @key: The key to decrypt with.
 * @mechanism: The mechanism type and parameters to use for decryption.
 * @input: (array length=n_input): data to decrypt
 * @n_input: length of the data to decrypt
 * @n_result: location to store the length of the result data
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @error: A location to place error information.
 *
 * Decrypt data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the data that was decrypted,
 *          or %NULL if an error occured
 */
guchar *
gck_session_decrypt_full (GckSession *self, GckObject *key, GckMechanism *mechanism,
                           const guchar *input, gsize n_input, gsize *n_result,
                           GCancellable *cancellable, GError **error)
{
	GckModule *module = NULL;
	CK_FUNCTION_LIST_PTR funcs;
	guchar *ret;

	g_object_get (self, "module", &module, NULL);
	g_return_val_if_fail (module != NULL, NULL);

	funcs = gck_module_get_functions (module);
	g_return_val_if_fail (module != NULL, NULL);

	ret = crypt_sync (self, key, mechanism, input, n_input, n_result, cancellable, error,
	                  funcs->C_DecryptInit, funcs->C_Decrypt);
	g_object_unref (module);
	return ret;
}

/**
 * gck_session_decrypt_async:
 * @self: The session.
 * @key: The key to decrypt with.
 * @mechanism: The mechanism type and parameters to use for decryption.
 * @input: (array length=n_input): data to decrypt
 * @n_input: length of the data to decrypt
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @callback: Called when the operation completes.
 * @user_data: A pointer to pass to the callback.
 *
 * Decrypt data in a mechanism specific manner. This call will
 * return immediately and complete asynchronously.
 */
void
gck_session_decrypt_async (GckSession *self, GckObject *key, GckMechanism *mechanism,
                            const guchar *input, gsize n_input, GCancellable *cancellable,
                            GAsyncReadyCallback callback, gpointer user_data)
{
	GckModule *module = NULL;
	CK_FUNCTION_LIST_PTR funcs;

	g_object_get (self, "module", &module, NULL);
	g_return_if_fail (module != NULL);

	funcs = gck_module_get_functions (module);
	g_return_if_fail (module != NULL);

	crypt_async (self, key, mechanism, input, n_input, cancellable, callback, user_data,
	             funcs->C_DecryptInit, funcs->C_Decrypt);
	g_object_unref (module);
}

/**
 * gck_session_decrypt_finish:
 * @self: The session.
 * @result: The result object passed to the callback.
 * @n_result: A location to store the length of the result data.
 * @error: A location to place error information.
 *
 * Get the result of an decryption operation.
 *
 * Returns: (transfer full) (array length=n_result): the data that was decrypted,
 *          or %NULL if an error occurred
 */
guchar*
gck_session_decrypt_finish (GckSession *self, GAsyncResult *result,
                             gsize *n_result, GError **error)
{
	return crypt_finish (self, result, n_result, error);
}

/* --------------------------------------------------------------------------------------------------
 * SIGN
 */

/**
 * gck_session_sign:
 * @self: The session.
 * @key: The key to sign with.
 * @mech_type: The mechanism type to use for signing.
 * @input: (array length=n_input): data to sign
 * @n_input: length of the data to sign
 * @n_result: location to store the length of the result data
 * @cancellable: Optional cancellation object, or %NULL
 * @error: A location to place an error.
 *
 * Sign data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: (transfer full) (array length=n_result): the data that was signed,
 *          or %NULL if an error occured
 */
guchar *
gck_session_sign (GckSession *self, GckObject *key, gulong mech_type, const guchar *input,
                   gsize n_input, gsize *n_result, GCancellable *cancellable, GError **error)
{
	GckMechanism mechanism = { mech_type, NULL, 0 };
	return gck_session_sign_full (self, key, &mechanism, input, n_input, n_result, NULL, error);
}

/**
 * gck_session_sign_full:
 * @self: The session.
 * @key: The key to sign with.
 * @mechanism: The mechanism type and parameters to use for signing.
 * @input: (array length=n_input): data to sign
 * @n_input: length of the data to sign
 * @n_result: location to store the length of the result data
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @error: A location to place error information.
 *
 * Sign data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: The data that was signed, or %NULL if an error occured.
 */
guchar*
gck_session_sign_full (GckSession *self, GckObject *key, GckMechanism *mechanism,
                        const guchar *input, gsize n_input, gsize *n_result,
                        GCancellable *cancellable, GError **error)
{
	GckModule *module = NULL;
	CK_FUNCTION_LIST_PTR funcs;
	guchar *ret;

	g_object_get (self, "module", &module, NULL);
	g_return_val_if_fail (module != NULL, NULL);

	funcs = gck_module_get_functions (module);
	g_return_val_if_fail (module != NULL, NULL);

	ret = crypt_sync (self, key, mechanism, input, n_input, n_result, cancellable, error,
	                  funcs->C_SignInit, funcs->C_Sign);
	g_object_unref (module);
	return ret;
}

/**
 * gck_session_sign_async:
 * @self: The session.
 * @key: The key to sign with.
 * @mechanism: The mechanism type and parameters to use for signing.
 * @input: (array length=n_input): data to sign
 * @n_input: length of the data to sign
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @callback: Called when the operation completes.
 * @user_data: A pointer to pass to the callback.
 *
 * Sign data in a mechanism specific manner. This call will
 * return immediately and complete asynchronously.
 */
void
gck_session_sign_async (GckSession *self, GckObject *key, GckMechanism *mechanism,
                         const guchar *input, gsize n_input, GCancellable *cancellable,
                         GAsyncReadyCallback callback, gpointer user_data)
{
	GckModule *module = NULL;
	CK_FUNCTION_LIST_PTR funcs;

	g_object_get (self, "module", &module, NULL);
	g_return_if_fail (module != NULL);

	funcs = gck_module_get_functions (module);
	g_return_if_fail (module != NULL);

	crypt_async (self, key, mechanism, input, n_input, cancellable, callback, user_data,
	             funcs->C_SignInit, funcs->C_Sign);
	g_object_unref (module);
}

/**
 * gck_session_sign_finish:
 * @self: The session.
 * @result: The result object passed to the callback.
 * @n_result: A location to store the length of the result data.
 * @error: A location to place error information.
 *
 * Get the result of an signing operation.
 *
 * Returns: (transfer full) (array length=n_result): the data that was signed,
 *          or %NULL if an error occurred
 */
guchar *
gck_session_sign_finish (GckSession *self, GAsyncResult *result,
                          gsize *n_result, GError **error)
{
	return crypt_finish (self, result, n_result, error);
}

/* --------------------------------------------------------------------------------------------------
 * VERIFY
 */

typedef struct _Verify {
	GckArguments base;

	/* Interaction */
	GckObject *key_object;
	GTlsInteraction *interaction;

	/* Input */
	CK_OBJECT_HANDLE key;
	GckMechanism mechanism;
	guchar *input;
	CK_ULONG n_input;
	guchar *signature;
	CK_ULONG n_signature;

} Verify;

static CK_RV
perform_verify (Verify *args)
{
	CK_RV rv;

	/* Initialize the crypt operation */
	rv = (args->base.pkcs11->C_VerifyInit) (args->base.handle, (CK_MECHANISM_PTR)&(args->mechanism), args->key);
	if (rv != CKR_OK)
		return rv;

	rv = _gck_session_authenticate_key (args->base.pkcs11, args->base.handle,
	                                    args->key_object, args->interaction, NULL);

	if (rv != CKR_OK)
		return rv;

	/* Do the actual verify */
	return (args->base.pkcs11->C_Verify) (args->base.handle, args->input, args->n_input,
	                                      args->signature, args->n_signature);
}

static void
free_verify (Verify *args)
{
	g_clear_object (&args->interaction);
	g_clear_object (&args->key_object);

	g_clear_pointer (&args->input, g_free);
	g_clear_pointer (&args->signature, g_free);
	g_free (args);
}

/**
 * gck_session_verify:
 * @self: The session.
 * @key: The key to verify with.
 * @mech_type: The mechanism type to use for verifying.
 * @input: (array length=n_input): data to verify
 * @n_input: length of the data to verify
 * @signature: (array length=n_signature): the signature
 * @n_signature: length of the signature
 * @cancellable: Optional cancellation object, or %NULL
 * @error: A location to place an error.
 *
 * Verify data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: %TRUE if the data verified correctly, otherwise a failure or error occurred.
 */
gboolean
gck_session_verify (GckSession *self, GckObject *key, gulong mech_type, const guchar *input,
                     gsize n_input, const guchar *signature, gsize n_signature, GCancellable *cancellable, GError **error)
{
	GckMechanism mechanism = { mech_type, NULL, 0 };
	return gck_session_verify_full (self, key, &mechanism, input, n_input,
	                                 signature, n_signature, NULL, error);
}

/**
 * gck_session_verify_full:
 * @self: The session.
 * @key: The key to verify with.
 * @mechanism: The mechanism type and parameters to use for signing.
 * @input: (array length=n_input): data to verify
 * @n_input: the length of the data to verify
 * @signature: (array length=n_signature): the signature
 * @n_signature: length of the signature
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @error: A location to place an error.
 *
 * Verify data in a mechanism specific manner. This call may
 * block for an indefinite period.
 *
 * Returns: %TRUE if the data verified correctly, otherwise a failure or error occurred.
 */
gboolean
gck_session_verify_full (GckSession *self, GckObject *key, GckMechanism *mechanism,
                          const guchar *input, gsize n_input, const guchar *signature,
                          gsize n_signature, GCancellable *cancellable, GError **error)
{
	Verify args;
	gboolean ret;

	g_return_val_if_fail (GCK_IS_OBJECT (key), FALSE);
	g_return_val_if_fail (mechanism, FALSE);

	memset (&args, 0, sizeof (args));
	g_object_get (key, "handle", &args.key, NULL);
	g_return_val_if_fail (args.key != 0, FALSE);

	/* Shallow copy of the mechanism structure */
	memcpy (&args.mechanism, mechanism, sizeof (args.mechanism));

	/* No need to copy in this case */
	args.input = (guchar*)input;
	args.n_input = n_input;
	args.signature = (guchar*)signature;
	args.n_signature = n_signature;

	args.key_object = key;
	args.interaction = gck_session_get_interaction (self);

	ret = _gck_call_sync (self, perform_verify, NULL, &args, cancellable, error);

	g_clear_object (&args.interaction);

	return ret;
}

/**
 * gck_session_verify_async:
 * @self: The session.
 * @key: The key to verify with.
 * @mechanism: The mechanism type and parameters to use for signing.
 * @input: (array length=n_input): data to verify
 * @n_input: the length of the data to verify
 * @signature: (array length=n_signature): the signature
 * @n_signature: the length of the signature
 * @cancellable: A GCancellable which can be used to cancel the operation.
 * @callback: Called when the operation completes.
 * @user_data: A pointer to pass to the callback.
 *
 * Verify data in a mechanism specific manner. This call returns
 * immediately and completes asynchronously.
 */
void
gck_session_verify_async (GckSession *self, GckObject *key, GckMechanism *mechanism,
                           const guchar *input, gsize n_input, const guchar *signature,
                           gsize n_signature, GCancellable *cancellable,
                           GAsyncReadyCallback callback, gpointer user_data)
{
	GckCall *call;
	Verify *args;

	call = _gck_call_async_prep (self, perform_verify, NULL, sizeof (*args), free_verify);
	args = _gck_call_get_arguments (call);

	g_return_if_fail (GCK_IS_OBJECT (key));
	g_return_if_fail (mechanism);

	g_object_get (key, "handle", &args->key, NULL);
	g_return_if_fail (args->key != 0);

	/* Shallow copy of the mechanism structure */
	memcpy (&args->mechanism, mechanism, sizeof (args->mechanism));

	args->input = input && n_input ? g_memdup2 (input, n_input) : NULL;
	args->n_input = n_input;
	args->signature = signature && n_signature ? g_memdup2 (signature, n_signature) : NULL;
	args->n_signature = n_signature;

	args->key_object = g_object_ref (key);
	args->interaction = gck_session_get_interaction (self);

	_gck_call_async_ready_go (call, self, cancellable, callback, user_data);
}

/**
 * gck_session_verify_finish:
 * @self: The session.
 * @result: The result object passed to the callback.
 * @error: A location to place error information.
 *
 * Get the result of an verify operation.
 *
 * Returns: %TRUE if the data verified correctly, otherwise a failure or error occurred.
 */
gboolean
gck_session_verify_finish (GckSession *self, GAsyncResult *result, GError **error)
{
	return _gck_call_basic_finish (result, error);
}

static void
update_password_for_token (GTlsPassword *password,
                           CK_TOKEN_INFO *token_info,
                           gboolean request_retry)
{
	GTlsPasswordFlags flags;
	gchar *label;

	label = gck_string_from_chars (token_info->label, sizeof (token_info->label));
	g_tls_password_set_description (password, label);
	g_free (label);

	flags = 0;
	if (request_retry)
		flags |= G_TLS_PASSWORD_RETRY;
	if (token_info && token_info->flags & CKF_USER_PIN_COUNT_LOW)
		flags |= G_TLS_PASSWORD_MANY_TRIES;
	if (token_info && token_info->flags & CKF_USER_PIN_FINAL_TRY)
		flags |= G_TLS_PASSWORD_FINAL_TRY;
	g_tls_password_set_flags (password, flags);
}

CK_RV
_gck_session_authenticate_token (CK_FUNCTION_LIST_PTR funcs,
                                 CK_SESSION_HANDLE session,
                                 GckSlot *token,
                                 GTlsInteraction *interaction,
                                 GCancellable *cancellable)
{
	CK_SESSION_INFO session_info;
	GTlsPassword *password = NULL;
	CK_TOKEN_INFO token_info;
	GTlsInteractionResult res;
	gboolean request_retry;
	CK_SLOT_ID slot_id;
	CK_BYTE_PTR pin;
	gsize n_pin;
	CK_RV rv = CKR_OK;
	GError *error = NULL;

	g_assert (funcs != NULL);
	g_assert (GCK_IS_SLOT (token));

	slot_id = gck_slot_get_handle (token);
	request_retry = FALSE;

	do {
		if (g_cancellable_is_cancelled (cancellable)) {
			rv = CKR_FUNCTION_CANCELED;
			break;
		}

		rv = (funcs->C_GetTokenInfo) (slot_id, &token_info);
		if (rv != CKR_OK) {
			g_warning ("couldn't get token info when logging in: %s",
			           gck_message_from_rv (rv));
			break;
		}

		/* No login necessary? */
		if ((token_info.flags & CKF_LOGIN_REQUIRED) == 0) {
			g_debug ("no login required for token, skipping login");
			rv = CKR_OK;
			break;
		}

		/* Next check if session is logged in? */
		rv = (funcs->C_GetSessionInfo) (session, &session_info);
		if (rv != CKR_OK) {
			g_warning ("couldn't get session info when logging in: %s",
			           gck_message_from_rv (rv));
			break;
		}

		/* Already logged in? */
		if (session_info.state == CKS_RW_USER_FUNCTIONS ||
		    session_info.state == CKS_RO_USER_FUNCTIONS ||
		    session_info.state == CKS_RW_SO_FUNCTIONS) {
			g_debug ("already logged in, skipping login");
			rv = CKR_OK;
			break;
		}

		if (token_info.flags & CKF_PROTECTED_AUTHENTICATION_PATH) {
			g_debug ("trying to log into session: protected authentication path, no password");

			/* No password passed for PAP */
			pin = NULL;
			n_pin = 0;


		/* Not protected auth path */
		} else {
			g_debug ("trying to log into session: want password %s",
			            request_retry ? "login was incorrect" : "");

			if (password == NULL)
				password = g_object_new (GCK_TYPE_PASSWORD, "token", token, NULL);

			update_password_for_token (password, &token_info, request_retry);

			if (interaction == NULL)
				res = G_TLS_INTERACTION_UNHANDLED;

			else
				res = g_tls_interaction_invoke_ask_password (interaction,
				                                             G_TLS_PASSWORD (password),
				                                             NULL, &error);

			if (res == G_TLS_INTERACTION_FAILED) {
				g_message ("interaction couldn't ask password: %s", error->message);
				rv = _gck_rv_from_error (error, CKR_USER_NOT_LOGGED_IN);
				g_clear_error (&error);
				break;

			} else if (res == G_TLS_INTERACTION_UNHANDLED) {
				g_message ("couldn't authenticate: no interaction handler");
				rv = CKR_USER_NOT_LOGGED_IN;
				break;
			}

			pin = (CK_BYTE_PTR)g_tls_password_get_value (password, &n_pin);
		}

		/* Try to log in */
		rv = (funcs->C_Login) (session, CKU_USER, (CK_BYTE_PTR)pin, (CK_ULONG)n_pin);

		/* Only one C_Login call if protected auth path */
		if (token_info.flags & CKF_PROTECTED_AUTHENTICATION_PATH)
			break;

		request_retry = TRUE;
	} while (rv == CKR_PIN_INCORRECT);

	g_clear_object (&password);

	return rv;
}

static void
update_password_for_key (GTlsPassword *password,
                         CK_TOKEN_INFO *token_info,
                         gboolean request_retry)
{
	GTlsPasswordFlags flags;

	flags = 0;
	if (request_retry)
		flags |= G_TLS_PASSWORD_RETRY;
	if (token_info && token_info->flags & CKF_USER_PIN_COUNT_LOW)
		flags |= G_TLS_PASSWORD_MANY_TRIES;
	if (token_info && token_info->flags & CKF_USER_PIN_FINAL_TRY)
		flags |= G_TLS_PASSWORD_FINAL_TRY;
	g_tls_password_set_flags (password, flags);
}

CK_RV
_gck_session_authenticate_key (CK_FUNCTION_LIST_PTR funcs,
                               CK_SESSION_HANDLE session,
                               GckObject *key,
                               GTlsInteraction *interaction,
                               GCancellable *cancellable)
{
	CK_ATTRIBUTE attrs[2];
	CK_SESSION_INFO session_info;
	CK_TOKEN_INFO token_info;
	GTlsPassword *password = NULL;
	CK_OBJECT_HANDLE handle;
	GTlsInteractionResult res;
	gboolean request_retry;
	GError *error = NULL;
	CK_BYTE_PTR pin;
	gsize pin_len;
	CK_BBOOL bvalue;
	gboolean got_label;
	CK_RV rv;

	g_assert (funcs != NULL);

	handle = gck_object_get_handle (key);

	attrs[0].type = CKA_LABEL;
	attrs[0].pValue = NULL;
	attrs[0].ulValueLen = 0;
	attrs[1].type = CKA_ALWAYS_AUTHENTICATE;
	attrs[1].pValue = &bvalue;
	attrs[1].ulValueLen = sizeof (bvalue);

	rv = (funcs->C_GetAttributeValue) (session, handle, attrs, 2);
	if (rv == CKR_ATTRIBUTE_TYPE_INVALID) {
		bvalue = CK_FALSE;

	} else if (rv != CKR_OK) {
		g_message ("couldn't check whether key requires authentication, assuming it doesn't: %s",
		           gck_message_from_rv (rv));
		return CKR_OK;
	}

	/* No authentication needed, on this object */
	if (bvalue != CK_TRUE) {
		g_debug ("key does not require authentication");
		return CKR_OK;
	}

	got_label = FALSE;
	request_retry = FALSE;

	do {
		if (g_cancellable_is_cancelled (cancellable)) {
			rv = CKR_FUNCTION_CANCELED;
			break;
		}

		rv = (funcs->C_GetSessionInfo) (session, &session_info);
		if (rv != CKR_OK) {
			g_warning ("couldn't get session info when authenticating key: %s",
			           gck_message_from_rv (rv));
			return rv;
		}

		rv = (funcs->C_GetTokenInfo) (session_info.slotID, &token_info);
		if (rv != CKR_OK) {
			g_warning ("couldn't get token info when authenticating key: %s",
			           gck_message_from_rv (rv));
			return rv;
		}

		/* Protected authentication path, just use NULL passwords */
		if (token_info.flags & CKF_PROTECTED_AUTHENTICATION_PATH) {

			password = NULL;
			pin = NULL;
			pin_len = 0;

		/* Need to prompt for a password */
		} else {
			g_debug ("trying to log into session: want password %s",
			         request_retry ? "login was incorrect" : "");

			if (password == NULL)
				password = g_object_new (GCK_TYPE_PASSWORD, "key", key, NULL);

			/* Set the password */
			update_password_for_key (password, &token_info, request_retry);

			/* Set the label properly */
			if (!got_label) {
				if (attrs[0].ulValueLen && attrs[0].ulValueLen != GCK_INVALID) {
					attrs[0].pValue = g_malloc0 (attrs[0].ulValueLen + 1);
					rv = (funcs->C_GetAttributeValue) (session, handle, attrs, 1);
					if (rv == CKR_OK) {
						((gchar *)attrs[0].pValue)[attrs[0].ulValueLen] = 0;
						g_tls_password_set_description (password, attrs[0].pValue);
					}
					g_free (attrs[0].pValue);
					attrs[0].pValue = NULL;
				}

				got_label = TRUE;
			}

			if (interaction == NULL)
				res = G_TLS_INTERACTION_UNHANDLED;

			else
				res = g_tls_interaction_invoke_ask_password (interaction,
				                                             G_TLS_PASSWORD (password),
				                                             NULL, &error);

			if (res == G_TLS_INTERACTION_FAILED) {
				g_message ("interaction couldn't ask password: %s", error->message);
				rv = _gck_rv_from_error (error, CKR_USER_NOT_LOGGED_IN);
				g_clear_error (&error);
				break;

			} else if (res == G_TLS_INTERACTION_UNHANDLED) {
				g_message ("couldn't authenticate: no interaction handler");
				rv = CKR_USER_NOT_LOGGED_IN;
				break;
			}

			pin = (CK_BYTE_PTR)g_tls_password_get_value (G_TLS_PASSWORD (password), &pin_len);
		}

		/* Try to log in */
		rv = (funcs->C_Login) (session, CKU_CONTEXT_SPECIFIC, pin, pin_len);

		/* Only one C_Login call if protected auth path */
		if (token_info.flags & CKF_PROTECTED_AUTHENTICATION_PATH)
			break;

		request_retry = TRUE;
	} while (rv == CKR_PIN_INCORRECT);

	g_clear_object (&password);

	return rv;
}