summaryrefslogtreecommitdiff
path: root/gck/gck-attributes.c
blob: 92c11a5d7edb4981bad960b981c60babfce3a5fa (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
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/* gck-attribute.c - 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 "pkcs11-trust-assertions.h"

#include "egg/egg-secure-memory.h"

#include <stdlib.h>
#include <string.h>

/**
 * GckAttribute:
 * @type: The attribute type, such as `CKA_LABEL`.
 * @value: (array length=length): The value of the attribute. May be %NULL.
 * @length: The length of the attribute. May be [const@INVALID] if the
 * attribute is invalid.
 *
 * This structure represents a PKCS#11 `CK_ATTRIBUTE`. These attributes contain
 * information about a PKCS#11 object. Use [method@Object.get] or
 * [method@Object.set] to set and attributes on an object.
 *
 * Although you are free to allocate a `GckAttribute` in your own code, no
 * functions in this library will operate on such an attribute.
 */

G_STATIC_ASSERT (sizeof (GckAttribute) == sizeof (CK_ATTRIBUTE));

struct _GckAttributes {
	GckAttribute *data;
	gulong count;
	gint refs;
};

typedef struct {
	GArray *array;
	gboolean secure;
	gint refs;
} GckRealBuilder;

G_STATIC_ASSERT (sizeof (GckRealBuilder) <= sizeof (GckBuilder));

EGG_SECURE_DECLARE (attributes);

#define MAX_ALIGN 16

static guchar *
value_take (gpointer data,
            gsize length,
            gboolean secure)
{
	gsize len = length + MAX_ALIGN;
	guchar *value;

	if (secure)
		value = egg_secure_realloc (data, len);
	else
		value = g_realloc (data, len);
	g_assert (value != NULL);

	memmove (value + MAX_ALIGN, value, length);
	g_atomic_int_set ((gint *)value, 1);
	return value + MAX_ALIGN;
}

static guchar *
value_blank (gsize length,
             gboolean secure)
{
	gsize len = length + MAX_ALIGN;
	guchar *value;

	if (secure)
		value = egg_secure_alloc (len);
	else
		value = g_malloc (len);
	g_assert (value != NULL);

	g_atomic_int_set ((gint *)value, 1);
	return value + MAX_ALIGN;
}

static guchar *
value_new (gconstpointer data,
           gsize length,
           gboolean secure)
{
	guchar *result;

	result = value_blank (length, secure);
	memcpy (result, data, length);
	return result;
}

static guchar *
value_ref (guchar *data)
{
	guchar *value = data - MAX_ALIGN;
	gint previous;

	g_assert (data != NULL);

	previous = g_atomic_int_add ((gint *)value, 1);
	if (G_UNLIKELY (previous <= 0)) {
		g_warning ("An owned GckAttribute value has been modified outside of the "
		           "gck library or an invalid attribute was passed to gck_builder_add_attribute()");
		return NULL;
	}

	return data;
}

static void
value_unref (guchar *data)
{
	guchar *value = data - MAX_ALIGN;

	g_assert (data != NULL);

	if (g_atomic_int_dec_and_test ((gint *)value)) {
		if (egg_secure_check (value))
			egg_secure_free (value);
		else
			g_free (value);
	}
}

G_DEFINE_BOXED_TYPE (GckBuilder, gck_builder,
                     gck_builder_ref, gck_builder_unref)

/**
 * GckBuilder:
 *
 * A builder for a set of attributes. Add attributes to a builder, and then use
 * [method@Builder.end] to get the completed [struct@Attributes].
 *
 * The fields of #GckBuilder are private and not to be accessed directly.
 */

/**
 * GckBuilderFlags:
 * @GCK_BUILDER_NONE: no special flags
 * @GCK_BUILDER_SECURE_MEMORY: use non-pageable memory for the values of the attributes
 *
 * Flags to be used with a [method@Builder.init_full] and [ctor@Builder.new].
 */

/**
 * GCK_BUILDER_INIT:
 *
 * Values that can be assigned to a #GckBuilder allocated on the stack.
 *
 * ```c
 * GckBuilder builder = GCK_BUILDER_INIT;
 * ```
 */

/**
 * gck_builder_new:
 * @flags: flags for the new builder
 *
 * Create a new `GckBuilder` not allocated on the stack, so it can be shared
 * across a single scope, and referenced / unreferenced.
 *
 * Normally a `GckBuilder` is created on the stack, and simply initialized.
 *
 * If the %GCK_BUILDER_SECURE_MEMORY flag is specified then non-pageable memory
 * will be used for the various values of the attributes in the builder
 *
 * Returns: (transfer full): a new builder, to be freed with gck_builder_unref()
 */
GckBuilder *
gck_builder_new (GckBuilderFlags flags)
{
	GckBuilder *builder;
	GckRealBuilder *real;
	builder = g_new0 (GckBuilder, 1);
	gck_builder_init_full (builder, flags);
	real = (GckRealBuilder *)builder;
	real->refs = 1;
	return builder;
}

/**
 * gck_builder_ref:
 * @builder: the builder
 *
 * Add a reference to a builder that was created with [ctor@Builder.new]. The
 * builder must later be unreferenced again with gck_builder_unref().
 *
 * It is an error to use this function on builders that were allocated on the
 * stack.
 *
 * Returns: the builder
 */
GckBuilder *
gck_builder_ref (GckBuilder *builder)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	gboolean stack;

	g_return_val_if_fail (builder != NULL, NULL);

	stack = g_atomic_int_add (&real->refs, 1) == 0;
	if G_UNLIKELY (stack) {
		g_warning ("Never call gck_builder_ref() on a stack allocated GckBuilder structure");
		return NULL;
	}

	return builder;
}

/**
 * gck_builder_unref:
 * @builder: (transfer full): the builder
 *
 * Unreferences a builder. If this was the last reference then the builder
 * is freed.
 *
 * It is an error to use this function on builders that were allocated on the
 * stack.
 */
void
gck_builder_unref (GckBuilder *builder)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	if (builder == NULL)
		return;

	if (g_atomic_int_dec_and_test (&real->refs)) {
		gck_builder_clear (builder);
		g_free (builder);
	}
}

/**
 * gck_builder_init_full:
 * @builder: the builder
 * @flags: the flags for the new builder
 *
 * Initialize a stack allocated builder, with the appropriate flags.
 *
 * If the %GCK_BUILDER_SECURE_MEMORY flag is specified then non-pageable memory
 * will be used for the various values of the attributes in the builder
 */
void
gck_builder_init_full (GckBuilder *builder,
                       GckBuilderFlags flags)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	g_return_if_fail (builder != NULL);

	memset (builder, 0, sizeof (GckBuilder));
	real->secure = flags & GCK_BUILDER_SECURE_MEMORY;
}

/**
 * gck_builder_init:
 * @builder: the builder
 *
 * Initialize a stack allocated builder, with the default flags.
 *
 * This is equivalent to initializing a builder variable with the
 * %GCK_BUILDER_INIT constant, or setting it to zeroed memory.
 *
 * ```c
 * // Equivalent ways of initializing a GckBuilder
 * GckBuilder builder = GCK_BUILDER_INIT;
 * GckBuilder builder2;
 * GckBuilder builder3;
 *
 * gck_builder_init (&builder2);
 *
 * memset (&builder3, 0, sizeof (builder3));
 * ```
 */
void
gck_builder_init (GckBuilder *builder)
{
	gck_builder_init_full (builder, GCK_BUILDER_NONE);
}

static GckAttribute *
builder_push (GckBuilder *builder,
              gulong attr_type)
{
	GckAttribute attr = { attr_type, NULL, 0 };
	GckRealBuilder *real = (GckRealBuilder *)builder;
	if (real->array == NULL)
		real->array = g_array_new (FALSE, TRUE, sizeof (GckAttribute));
	g_array_append_val (real->array, attr);
	return &g_array_index (real->array, GckAttribute, real->array->len - 1);
}

static void
builder_clear (GckAttribute *attr)
{
	attr->length = 0;
	if (attr->value)
		value_unref (attr->value);
	attr->value = NULL;
}

static GckAttribute *
find_attribute (GckAttribute *attrs,
                gsize n_attrs,
                gulong attr_type)
{
	guint i;

	for (i = 0; i < n_attrs; ++i) {
		if (attrs[i].type == attr_type)
			return attrs + i;
	}

	return NULL;
}

static GckAttribute *
builder_clear_or_push (GckBuilder *builder,
                       gulong attr_type)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttribute *attr = NULL;

	if (real->array)
		attr = find_attribute ((GckAttribute *)real->array->data,
		                       real->array->len, attr_type);
	if (attr == NULL)
		attr = builder_push (builder, attr_type);
	else
		builder_clear (attr);
	return attr;
}

static void
builder_copy (GckBuilder *builder,
              const GckAttribute *attr,
              gboolean performing_set)
{
	GckAttribute *copy;

	if (performing_set)
		copy = builder_clear_or_push (builder, attr->type);
	else
		copy = builder_push (builder, attr->type);
	if (attr->length == G_MAXULONG) {
		copy->value = NULL;
		copy->length = G_MAXULONG;
	} else if (attr->value == NULL) {
		copy->value = NULL;
		copy->length = 0;
	} else {
		copy->value = value_ref (attr->value);
		copy->length = attr->length;
	}
}

/**
 * gck_builder_copy:
 * @builder: the builder to copy
 *
 * Make a copy of the builder and its state. The new builder is allocated
 * with [ctor@Builder.new] and should be freed with gck_builder_unref().
 *
 * Attribute value memory is automatically shared between the two builders,
 * and is only freed when both are gone.
 *
 * Returns: (transfer full): the builder copy, which should be freed with
 *          gck_builder_unref().
 */
GckBuilder *
gck_builder_copy (GckBuilder *builder)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckBuilder *copy;
	guint i;

	if (builder == NULL)
		return NULL;

	copy = gck_builder_new (real->secure ? GCK_BUILDER_SECURE_MEMORY : GCK_BUILDER_NONE);
	for (i = 0; real->array && i < real->array->len; i++)
		builder_copy (copy, &g_array_index (real->array, GckAttribute, i), FALSE);

	return copy;
}

/**
 * gck_builder_take_data:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: (transfer full) (array length=length) (nullable): the new
 *         attribute memory
 * @length: the length of the memory
 *
 * Add a new attribute to the builder with an arbitrary value. Unconditionally
 * adds a new attribute, even if one with the same @attr_type already exists.
 *
 * Ownership of the @value memory is taken by the builder, may be reallocated,
 * and is eventually freed with g_free(). The memory must have been allocated
 * using the standard GLib memory allocation routines.
 *
 * %NULL may be specified for the @value argument, in which case an empty
 * attribute is created. [const@INVALID] may be specified for the length, in
 * which case an invalid attribute is created in the PKCS#11 style.
 */
void
gck_builder_take_data (GckBuilder *builder,
                       gulong attr_type,
                       guchar *value,
                       gsize length)
{
	GckAttribute *attr;
	gboolean secure;

	g_return_if_fail (builder != NULL);

	secure = value && egg_secure_check (value);

	attr = builder_push (builder, attr_type);
	if (length == G_MAXULONG) {
		if (secure)
			egg_secure_free (value);
		else
			g_free (value);
		attr->value = NULL;
		attr->length = G_MAXULONG;
	} else if (value == NULL) {
		attr->value = NULL;
		attr->length = 0;
	} else {
		attr->value = value_take (value, length, secure);
		attr->length = length;
	}
}

/**
 * gck_builder_add_data:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: (array length=length) (nullable): the new attribute memory
 * @length: the length of the memory
 *
 * Add a new attribute to the builder with an arbitrary value. Unconditionally
 * adds a new attribute, even if one with the same @attr_type already exists.
 *
 * The memory in @value is copied by the builder.
 *
 * %NULL may be specified for the @value argument, in which case an empty
 * attribute is created. [const@INVALID] may be specified for the length, in
 * which case an invalid attribute is created in the PKCS#11 style.
 */
void
gck_builder_add_data (GckBuilder *builder,
                      gulong attr_type,
                      const guchar *value,
                      gsize length)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttribute *attr;

	g_return_if_fail (builder != NULL);

	attr = builder_push (builder, attr_type);
	if (length == G_MAXULONG) {
		attr->value = NULL;
		attr->length = G_MAXULONG;
	} else if (value == NULL) {
		attr->value = NULL;
		attr->length = 0;
	} else {
		attr->value = value_new (value, length,
		                         real->secure || egg_secure_check (value));
		attr->length = length;
	}
}

/**
 * gck_builder_set_data:
 * @builder: the builder
 * @attr_type: the attribute type
 * @value: (array length=length) (nullable): the new attribute memory
 * @length: the length of the memory
 *
 * Set a new attribute to the builder with an arbitrary value. If an attribute
 * with @attr_type already exists in the builder then it is changed to the new
 * value, otherwise an attribute is added.
 *
 * The memory in @value is copied by the builder.
 *
 * %NULL may be specified for the @value argument, in which case an empty
 * attribute is created. [const@INVALID] may be specified for the length, in
 * which case an invalid attribute is created in the PKCS#11 style.
 */
void
gck_builder_set_data (GckBuilder *builder,
                      gulong attr_type,
                      const guchar *value,
                      gsize length)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttribute *attr;

	g_return_if_fail (builder != NULL);

	attr = builder_clear_or_push (builder, attr_type);
	if (length == G_MAXULONG) {
		attr->value = NULL;
		attr->length = G_MAXULONG;
	} else if (value == NULL) {
		attr->value = NULL;
		attr->length = 0;
	} else {
		attr->value = value_new (value, length,
		                         real->secure || egg_secure_check (value));
		attr->length = length;
	}
}

/**
 * gck_builder_add_empty:
 * @builder: the builder
 * @attr_type: the new attribute type
 *
 * Add a new attribute to the builder that is empty. Unconditionally
 * adds a new attribute, even if one with the same @attr_type already exists.
 */
void
gck_builder_add_empty (GckBuilder *builder,
                       gulong attr_type)
{
	g_return_if_fail (builder != NULL);

	builder_push (builder, attr_type);
}

/**
 * gck_builder_set_empty:
 * @builder: the builder
 * @attr_type: the attribute type
 *
 * Set an attribute on the builder that is empty. If an attribute
 * with @attr_type already exists in the builder then it is changed to the new
 * value, otherwise an attribute is added.
 */
void
gck_builder_set_empty (GckBuilder *builder,
                       gulong attr_type)
{
	g_return_if_fail (builder != NULL);

	builder_clear_or_push (builder, attr_type);
}

/**
 * gck_builder_add_invalid:
 * @builder: the builder
 * @attr_type: the new attribute type
 *
 * Add a new attribute to the builder that is invalid in the PKCS#11 sense.
 * Unconditionally adds a new attribute, even if one with the same @attr_type
 * already exists.
 */
void
gck_builder_add_invalid (GckBuilder *builder,
                         gulong attr_type)
{
	GckAttribute *attr;

	g_return_if_fail (builder != NULL);

	attr = builder_push (builder, attr_type);
	attr->length = (gulong)-1;
}

/**
 * gck_builder_set_invalid:
 * @builder: the builder
 * @attr_type: the attribute type
 *
 * Set an attribute on the builder that is invalid in the PKCS#11 sense.
 * If an attribute with @attr_type already exists in the builder then it is
 * changed to the new value, otherwise an attribute is added.
 */
void
gck_builder_set_invalid (GckBuilder *builder,
                         gulong attr_type)
{
	GckAttribute *attr;

	g_return_if_fail (builder != NULL);

	attr = builder_clear_or_push (builder, attr_type);
	attr->length = (gulong)-1;
}

/**
 * gck_builder_add_ulong:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Add a new attribute to the builder for the unsigned long @value.
 * Unconditionally adds a new attribute, even if one with the same @attr_type
 * already exists.
 */
void
gck_builder_add_ulong (GckBuilder *builder,
                       gulong attr_type,
                       gulong value)
{
	CK_ULONG uval = value;
	gck_builder_add_data (builder, attr_type,
	                      (const guchar *)&uval, sizeof (uval));
}

/**
 * gck_builder_set_ulong:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Set an attribute on the builder for the unsigned long @value.
 * If an attribute with @attr_type already exists in the builder then it is
 * changed to the new value, otherwise an attribute is added.
 */
void
gck_builder_set_ulong (GckBuilder *builder,
                       gulong attr_type,
                       gulong value)
{
	CK_ULONG uval = value;
	gck_builder_set_data (builder, attr_type,
	                      (const guchar *)&uval, sizeof (uval));
}

/**
 * gck_builder_add_boolean:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Add a new attribute to the builder for the boolean @value.
 * Unconditionally adds a new attribute, even if one with the same @attr_type
 * already exists.
 */
void
gck_builder_add_boolean (GckBuilder *builder,
                         gulong attr_type,
                         gboolean value)
{
	CK_BBOOL bval = value ? CK_TRUE : CK_FALSE;
	gck_builder_add_data (builder, attr_type,
	                      (const guchar *)&bval, sizeof (bval));
}

/**
 * gck_builder_set_boolean:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Set an attribute on the builder for the boolean @value.
 * If an attribute with @attr_type already exists in the builder then it is
 * changed to the new value, otherwise an attribute is added.
 */
void
gck_builder_set_boolean (GckBuilder *builder,
                         gulong attr_type,
                         gboolean value)
{
	CK_BBOOL bval = value ? CK_TRUE : CK_FALSE;
	gck_builder_set_data (builder, attr_type,
	                      (const guchar *)&bval, sizeof (bval));
}

static void
convert_gdate_to_ckdate (const GDate *value,
                         CK_DATE *date)
{
	gchar buffer[9];
	g_snprintf (buffer, sizeof (buffer), "%04d%02d%02d",
	            (int)g_date_get_year (value),
	            (int)g_date_get_month (value),
	            (int)g_date_get_day (value));
	memcpy (&date->year, buffer + 0, 4);
	memcpy (&date->month, buffer + 4, 2);
	memcpy (&date->day, buffer + 6, 2);
}

/**
 * gck_builder_add_date:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Add a new attribute to the builder for the date @value.
 * Unconditionally adds a new attribute, even if one with the same @attr_type
 * already exists.
 */
void
gck_builder_add_date (GckBuilder *builder,
                      gulong attr_type,
                      const GDate *value)
{
	CK_DATE date;

	g_return_if_fail (value != NULL);

	convert_gdate_to_ckdate (value, &date);
	gck_builder_add_data (builder, attr_type,
	                      (const guchar *)&date, sizeof (CK_DATE));
}

/**
 * gck_builder_set_date:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Set an attribute on the builder for the date @value.
 * If an attribute with @attr_type already exists in the builder then it is
 * changed to the new value, otherwise an attribute is added.
 */
void
gck_builder_set_date (GckBuilder *builder,
                      gulong attr_type,
                      const GDate *value)
{
	CK_DATE date;

	g_return_if_fail (value != NULL);

	convert_gdate_to_ckdate (value, &date);
	gck_builder_set_data (builder, attr_type,
	                      (const guchar *)&date, sizeof (CK_DATE));
}

/**
 * gck_builder_add_string:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: (nullable): the attribute value
 *
 * Add a new attribute to the builder for the string @value or %NULL.
 * Unconditionally adds a new attribute, even if one with the same @attr_type
 * already exists.
 */
void
gck_builder_add_string (GckBuilder *builder,
                        gulong attr_type,
                        const gchar *value)
{
	gck_builder_add_data (builder, attr_type,
	                      (const guchar *)value, value ? strlen (value) : 0);
}

/**
 * gck_builder_set_string:
 * @builder: the builder
 * @attr_type: the new attribute type
 * @value: the attribute value
 *
 * Set an attribute on the builder for the string @value or %NULL.
 * If an attribute with @attr_type already exists in the builder then it is
 * changed to the new value, otherwise an attribute is added.
 */
void
gck_builder_set_string (GckBuilder *builder,
                        gulong attr_type,
                        const gchar *value)
{
	gck_builder_set_data (builder, attr_type,
	                      (const guchar *)value, value ? strlen (value) : 0);
}

/**
 * gck_builder_add_attribute:
 * @builder: the builder
 * @attr: the attribute to add
 *
 * Add an attribute to the builder. The attribute is added unconditionally whether
 * or not an attribute with the same type already exists on the builder.
 *
 * The @attr attribute must have been created or owned by the Gck library.
 * If you call this function on an arbitrary `GckAttribute` that is allocated on
 * the stack or elsewhere, then this will result in undefined behavior.
 *
 * As an optimization, the attribute memory value is automatically shared
 * between the attribute and the builder.
 */
void
gck_builder_add_attribute (GckBuilder *builder,
                           const GckAttribute *attr)
{
	g_return_if_fail (builder != NULL);
	g_return_if_fail (attr != NULL);

	builder_copy (builder, attr, FALSE);
}

/**
 * gck_builder_add_all:
 * @builder: the builder
 * @attrs: the attributes to add
 *
 * Add all the @attrs attributes to the builder. The attributes are added
 * uncondititionally whether or not attributes with the same types already
 * exist in the builder.
 *
 * As an optimization, the attribute memory values are automatically shared
 * between the attributes and the builder.
 */
void
gck_builder_add_all (GckBuilder *builder,
                     GckAttributes *attrs)
{
	gulong i;

	g_return_if_fail (builder != NULL);
	g_return_if_fail (attrs != NULL);

	for (i = 0; i < attrs->count; i++)
		builder_copy (builder, &attrs->data[i], FALSE);
}

/**
 * gck_builder_add_only: (skip)
 * @builder: the builder
 * @attrs: the attributes to add
 * @only_type: the first type of attribute to add
 * @...: the remaining attribute types to add, ending with [const@INVALID]
 *
 * Add the attributes specified in the argument list from @attrs to the
 * builder. The attributes are added uncondititionally whether or not
 * attributes with the same types already exist in the builder.
 *
 * The variable arguments must be unsigned longs.
 *
 * ```c
 * // Add the CKA_ID and CKA_CLASS attributes from attrs to builder
 * gck_builder_add_only (builder, attrs, CKA_ID, CKA_CLASS, GCK_INVALID);
 * ```
 *
 * As an optimization, the attribute memory values are automatically shared
 * between the attributes and the builder.
 */
void
gck_builder_add_only (GckBuilder *builder,
                      GckAttributes *attrs,
                      gulong only_type,
                      ...)
{
	GArray *types;
	va_list va;

	g_return_if_fail (builder != NULL);
	g_return_if_fail (attrs != NULL);

	types = g_array_new (FALSE, FALSE, sizeof (gulong));

	va_start (va, only_type);
	while (only_type != GCK_INVALID) {
		g_array_append_val (types, only_type);
		only_type = va_arg (va, gulong);
	}
	va_end (va);

	gck_builder_add_onlyv (builder, attrs, (gulong *)types->data, types->len);
	g_array_free (types, TRUE);
}

/**
 * gck_builder_add_onlyv: (rename-to gck_builder_add_only)
 * @builder: the builder
 * @attrs: the attributes to add
 * @only_types: (array length=n_only_types): the types of attributes to add
 * @n_only_types: the number of attributes
 *
 * Add the attributes with the types in @only_types from @attrs to the
 * builder. The attributes are added uncondititionally whether or not
 * attributes with the same types already exist in the builder.
 *
 * ```c
 * // Add the CKA_ID and CKA_CLASS attributes from attrs to builder
 * gulong only[] = { CKA_ID, CKA_CLASS };
 * gck_builder_add_onlyv (builder, attrs, only, 2);
 * ```
 *
 * As an optimization, the attribute memory values are automatically shared
 * between the attributes and the builder.
 */
void
gck_builder_add_onlyv (GckBuilder *builder,
                       GckAttributes *attrs,
                       const gulong *only_types,
                       guint n_only_types)
{
	gulong i;
	guint j;

	g_return_if_fail (builder != NULL);
	g_return_if_fail (attrs != NULL);

	for (i = 0; i < attrs->count; i++) {
		for (j = 0; j < n_only_types; j++) {
			if (attrs->data[i].type == only_types[j])
				builder_copy (builder, &attrs->data[i], FALSE);
		}
	}
}

/**
 * gck_builder_add_except: (skip)
 * @builder: the builder
 * @attrs: the attributes to add
 * @except_type: the first type of attribute to to exclude
 * @...: the remaining attribute types to exclude, ending with [const@INVALID]
 *
 * Add the attributes in @attrs to the builder, with the exception of those
 * in the argument list. The attributes are added uncondititionally whether or
 * not attributes with the same types already exist in the builder.
 *
 * The variable arguments must be unsigned longs.
 *
 * ```c
 * // Add all attributes in attrs except CKA_CLASS to the builder
 * gck_builder_add_except (builder, attrs, CKA_CLASS, GCK_INVALID);
 * ```
 *
 * As an optimization, the attribute memory values are automatically shared
 * between the attributes and the builder.
 */
void
gck_builder_add_except (GckBuilder *builder,
                        GckAttributes *attrs,
                        gulong except_type,
                        ...)
{
	GArray *types;
	va_list va;

	g_return_if_fail (builder != NULL);
	g_return_if_fail (attrs != NULL);

	types = g_array_new (FALSE, FALSE, sizeof (gulong));

	va_start (va, except_type);
	while (except_type != GCK_INVALID) {
		g_array_append_val (types, except_type);
		except_type = va_arg (va, gulong);
	}
	va_end (va);

	gck_builder_add_exceptv (builder, attrs, (gulong *)types->data, types->len);
	g_array_free (types, TRUE);
}

/**
 * gck_builder_add_exceptv: (skip)
 * @builder: the builder
 * @attrs: the attributes to add
 * @except_types: (array length=n_except_types): the except types
 * @n_except_types: the number of except types
 *
 * Add the attributes in @attrs to the builder, with the exception of those
 * whose types are specified in @except_types. The attributes are added
 * uncondititionally whether or not attributes with the same types already
 * exist in the builder.
 *
 * ```c
 * // Add all attributes in attrs except CKA_CLASS to the builder
 * unsigned long except_types[] = { CKA_CLASS };
 * gck_builder_add_exceptv (builder, attrs, except_types, 1);
 * ```
 *
 * As an optimization, the attribute memory values are automatically shared
 * between the attributes and the builder.
 */
void
gck_builder_add_exceptv (GckBuilder *builder,
                         GckAttributes *attrs,
                         const gulong *except_types,
                         guint n_except_types)
{
	gulong i;
	guint j;

	g_return_if_fail (builder != NULL);
	g_return_if_fail (attrs != NULL);

	for (i = 0; i < attrs->count; i++) {
		for (j = 0; j < n_except_types; j++) {
			if (attrs->data[i].type == except_types[j])
				break;
		}
		if (j == n_except_types)
			builder_copy (builder, &attrs->data[i], FALSE);
	}
}

/**
 * gck_builder_set_all:
 * @builder: the builder
 * @attrs: the attributes to set
 *
 * Set all the @attrs attributes to the builder. If any attributes with the
 * same types are already present in the builder, then those attributes are
 * changed to the new values.
 *
 * As an optimization, the attribute memory values are automatically shared
 * between the attributes and the builder.
 */
void
gck_builder_set_all (GckBuilder *builder,
                     GckAttributes *attrs)
{
	gulong i;

	g_return_if_fail (builder != NULL);
	g_return_if_fail (attrs != NULL);

	for (i = 0; i < attrs->count; i++)
		builder_copy (builder, &attrs->data[i], TRUE);
}

/**
 * gck_builder_find:
 * @builder: the builder
 * @attr_type: the type of attribute to find
 *
 * Find an attribute in the builder. Both valid and invalid attributes (in
 * the PKCS#11 sense) are returned. If multiple attributes exist for the given
 * attribute type, then the first one is returned.
 *
 * The returned [struct@Attribute] is owned by the builder and may not be
 * modified in any way. It is only valid until another attribute is added to or
 * set on the builder, or until the builder is cleared or unreferenced.
 *
 * Returns: the attribute or %NULL if not found
 */
const GckAttribute *
gck_builder_find (GckBuilder *builder,
                  gulong attr_type)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	g_return_val_if_fail (builder != NULL, NULL);

	if (real->array == NULL)
		return NULL;

	return find_attribute ((GckAttribute *)real->array->data,
	                       real->array->len, attr_type);
}

static gboolean
find_attribute_boolean (GckAttribute *attrs,
                        gsize n_attrs,
                        gulong attr_type,
                        gboolean *value)
{
	GckAttribute *attr;

	attr = find_attribute (attrs, n_attrs, attr_type);
	if (!attr || gck_attribute_is_invalid (attr))
		return FALSE;
	return gck_value_to_boolean (attr->value, attr->length, value);
}

/**
 * gck_builder_find_boolean:
 * @builder: the builder
 * @attr_type: the type of attribute to find
 * @value: (out): the location to place the found value
 *
 * Find a boolean attribute in the builder that has the type @attr_type, is
 * of the correct boolean size, and is not invalid in the PKCS#11 sense.
 * If multiple attributes exist for the given attribute type, then the first\
 * one is returned.
 *
 * Returns: whether a valid boolean attribute was found
 */
gboolean
gck_builder_find_boolean (GckBuilder *builder,
                          gulong attr_type,
                          gboolean *value)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	g_return_val_if_fail (builder != NULL, FALSE);
	g_return_val_if_fail (value != NULL, FALSE);

	if (real->array == NULL)
		return FALSE;

	return find_attribute_boolean ((GckAttribute *)real->array->data,
	                               real->array->len, attr_type, value);
}

static gboolean
find_attribute_ulong (GckAttribute *attrs,
                      gsize n_attrs,
                      gulong attr_type,
                      gulong *value)
{
	GckAttribute *attr;

	attr = find_attribute (attrs, n_attrs, attr_type);
	if (!attr || gck_attribute_is_invalid (attr))
		return FALSE;
	return gck_value_to_ulong (attr->value, attr->length, value);
}

/**
 * gck_builder_find_ulong:
 * @builder: the builder
 * @attr_type: the type of attribute to find
 * @value: (out): the location to place the found value
 *
 * Find a unsigned long attribute in the builder that has the type @attr_type,
 * is of the correct unsigned long size, and is not invalid in the PKCS#11 sense.
 * If multiple attributes exist for the given attribute type, then the first
 * one is returned.
 *
 * Returns: whether a valid unsigned long attribute was found
 */
gboolean
gck_builder_find_ulong (GckBuilder *builder,
                        gulong attr_type,
                        gulong *value)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	g_return_val_if_fail (builder != NULL, FALSE);
	g_return_val_if_fail (value != NULL, FALSE);

	if (real->array == NULL)
		return FALSE;

	return find_attribute_ulong ((GckAttribute *)real->array->data,
	                             real->array->len, attr_type, value);
}

static gboolean
find_attribute_string (GckAttribute *attrs,
                       gsize n_attrs,
                       gulong attr_type,
                       gchar **value)
{
	GckAttribute *attr;
	gchar *string;

	attr = find_attribute (attrs, n_attrs, attr_type);
	if (!attr || gck_attribute_is_invalid (attr))
		return FALSE;
	string = gck_attribute_get_string (attr);
	if (string == NULL)
		return FALSE;
	*value = string;
	return TRUE;
}

/**
 * gck_builder_find_string:
 * @builder: the builder
 * @attr_type: the type of attribute to find
 * @value: (out): the location to place the found value
 *
 * Find a string attribute in the builder that has the type @attr_type, has a
 * non %NULL value pointer, and is not invalid in the PKCS#11 sense.
 * If multiple attributes exist for the given attribute type, then the first
 * one is returned.
 *
 * Returns: whether a valid string attribute was found
 */
gboolean
gck_builder_find_string (GckBuilder *builder,
                         gulong attr_type,
                         gchar **value)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	g_return_val_if_fail (builder != NULL, FALSE);
	g_return_val_if_fail (value != NULL, FALSE);

	if (real->array == NULL)
		return FALSE;

	return find_attribute_string ((GckAttribute *)real->array->data,
	                              real->array->len, attr_type, value);
}

static gboolean
find_attribute_date (GckAttribute *attrs,
                     gsize n_attrs,
                     gulong attr_type,
                     GDate *value)
{
	GckAttribute *attr;

	attr = find_attribute (attrs, n_attrs, attr_type);
	if (!attr || gck_attribute_is_invalid (attr))
		return FALSE;
	gck_attribute_get_date (attr, value);
	return TRUE;
}

/**
 * gck_builder_find_date:
 * @builder: the builder
 * @attr_type: the type of attribute to find
 * @value: (out): the location to place the found value
 *
 * Find a date attribute in the builder that has the type @attr_type, is of
 * the correct date size, and is not invalid in the PKCS#11 sense.
 * If multiple attributes exist for the given attribute type, then the first
 * one is returned.
 *
 * Returns: whether a valid date attribute was found
 */
gboolean
gck_builder_find_date (GckBuilder *builder,
                       gulong attr_type,
                       GDate *value)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;

	g_return_val_if_fail (builder != NULL, FALSE);
	g_return_val_if_fail (value != NULL, FALSE);

	if (real->array == NULL)
		return FALSE;

	return find_attribute_date ((GckAttribute *)real->array->data,
	                            real->array->len, attr_type, value);
}

/**
 * gck_builder_end:
 * @builder: the builder
 *
 * Take the attributes that have been built in the #GckBuilder. The builder
 * will no longer contain any attributes after this function call.
 *
 * Returns: (transfer full): the attributes, which should be freed with
 *          gck_attributes_unref()
 */
GckAttributes *
gck_builder_end (GckBuilder *builder)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttributes *attrs;
	gpointer data;
	gulong length;

	g_return_val_if_fail (builder != NULL, NULL);

	if (real->array) {
		length = real->array->len;
		data = g_array_free (real->array, FALSE);
		real->array = NULL;
	} else {
		length = 0;
		data = NULL;
	}

	attrs = g_new0 (GckAttributes, 1);
	attrs->count = length;
	attrs->data = data;
	attrs->refs = 1;

	return attrs;
}

/**
 * gck_builder_clear:
 * @builder: the builder
 *
 * Clear the builder and release all allocated memory. The builder may be used
 * again to build another set of attributes after this function call.
 *
 * If memory is shared between this builder and other attributes, then that
 * memory is only freed when both of them are cleared or unreferenced.
 */
void
gck_builder_clear (GckBuilder *builder)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttribute *attr;
	guint i;

	g_return_if_fail (builder != NULL);

	if (real->array == NULL)
		return;

	for (i = 0; i < real->array->len; i++) {
		attr = &g_array_index (real->array, GckAttribute, i);
		builder_clear (attr);
	}

	g_array_free (real->array, TRUE);
	real->array = NULL;
}

/**
 * gck_attribute_is_invalid:
 * @attr: The attribute to check.
 *
 * Check if the PKCS#11 attribute represents 'invalid' or 'not found'
 * according to the PKCS#11 spec. That is, having length
 * of (CK_ULONG)-1.
 *
 * Return value: Whether the attribute represents invalid or not.
 */
gboolean
gck_attribute_is_invalid (const GckAttribute *attr)
{
	g_return_val_if_fail (attr, TRUE);
	return attr->length == (gulong)-1;
}

/**
 * gck_attribute_get_boolean:
 * @attr: The attribute to retrieve value from.
 *
 * Get the CK_BBOOL of a PKCS#11 attribute. No conversion
 * is performed. It is an error to pass an attribute to this
 * function unless you're know it's supposed to contain a
 * boolean value.
 *
 * Return value: The boolean value of the attribute.
 */
gboolean
gck_attribute_get_boolean (const GckAttribute *attr)
{
	gboolean value;

	g_return_val_if_fail (attr, FALSE);
	if (gck_attribute_is_invalid (attr))
		return FALSE;
	if (!gck_value_to_boolean (attr->value, attr->length, &value))
		g_return_val_if_reached (FALSE);
	return value;
}

/**
 * gck_attribute_get_ulong:
 * @attr: The attribute to retrieve value from.
 *
 * Get the CK_ULONG value of a PKCS#11 attribute. No
 * conversion is performed. It is an error to pass an attribute
 * to this function unless you're know it's supposed to contain
 * a value of the right type.
 *
 * Return value: The ulong value of the attribute.
 */
gulong
gck_attribute_get_ulong (const GckAttribute *attr)
{
	gulong value;

	g_return_val_if_fail (attr, FALSE);
	if (gck_attribute_is_invalid (attr))
		return 0;
	if (!gck_value_to_ulong (attr->value, attr->length, &value))
		g_return_val_if_reached ((gulong)-1);
	return value;
}

/**
 * gck_attribute_get_string:
 * @attr: The attribute to retrieve value from.
 *
 * Get the string value of a PKCS#11 attribute. No
 * conversion is performed. It is an error to pass an attribute
 * to this function unless you're know it's supposed to contain
 * a value of the right type.
 *
 * Return value: (nullable): a null terminated string, to be freed with
 *               g_free(), or %NULL if the value was invalid
 */
gchar*
gck_attribute_get_string (const GckAttribute *attr)
{
	g_return_val_if_fail (attr, NULL);

	if (gck_attribute_is_invalid (attr))
		return NULL;
	if (!attr->value)
		return NULL;

	return g_strndup ((gchar*)attr->value, attr->length);
}

/**
 * gck_attribute_get_date:
 * @attr: The attribute to retrieve value from.
 * @value: The date value to fill in with the parsed date.
 *
 * Get the CK_DATE of a PKCS#11 attribute. No
 * conversion is performed. It is an error to pass an attribute
 * to this function unless you're know it's supposed to contain
 * a value of the right type.
 */
void
gck_attribute_get_date (const GckAttribute *attr,
                        GDate *value)
{
	guint year, month, day;
	gchar buffer[5];
	CK_DATE *date;
	gchar *end;

	g_return_if_fail (attr);

	if (gck_attribute_is_invalid (attr)) {
		g_date_clear (value, 1);
		return;
	}

	g_return_if_fail (attr->length == sizeof (CK_DATE));
	g_return_if_fail (attr->value);
	date = (CK_DATE*)attr->value;

	memset (&buffer, 0, sizeof (buffer));
	memcpy (buffer, date->year, 4);
	year = strtol (buffer, &end, 10);
	g_return_if_fail (end != buffer && !*end);

	memset (&buffer, 0, sizeof (buffer));
	memcpy (buffer, date->month, 2);
	month = strtol (buffer, &end, 10);
	g_return_if_fail (end != buffer && !*end);

	memset (&buffer, 0, sizeof (buffer));
	memcpy (buffer, date->day, 2);
	day = strtol (buffer, &end, 10);
	g_return_if_fail (end != buffer && !*end);

	g_date_set_dmy (value, day, month, year);
}

/**
 * gck_attribute_get_data:
 * @attr: an attribute
 * @length: the length of the returned data
 *
 * Get the raw value in the attribute.
 *
 * This is useful from scripting languages. C callers will generally
 * access the #GckAttribute struct directly.
 *
 * This function will %NULL if the attribute contains empty or invalid
 * data. The returned data must not be modified and is only valid
 * as long as this @attribute.
 *
 * Returns: (transfer none) (array length=length): the value data or %NULL
 */
const guchar *
gck_attribute_get_data (const GckAttribute *attr,
                        gsize *length)
{
	g_return_val_if_fail (attr != NULL, NULL);

	if (attr->length == G_MAXULONG) {
		*length = 0;
		return NULL;
	}
	*length = attr->length;
	return attr->value;
}

/**
 * gck_attribute_init: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: (array length=length): The raw value of the attribute.
 * @length: The length of the raw value.
 *
 * Initialize a PKCS#11 attribute. This copies the value memory
 * into an internal buffer.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init (GckAttribute *attr,
                    gulong attr_type,
                    const guchar *value,
                    gsize length)
{
	g_return_if_fail (attr != NULL);

	attr->type = attr_type;
	if (length == G_MAXULONG) {
		attr->value = NULL;
		attr->length = G_MAXULONG;
	} else if (value == NULL) {
		attr->value = NULL;
		attr->length = 0;
	} else {
		attr->value = value_new (value, length, egg_secure_check (value));
		attr->length = length;
	}
}

/**
 * gck_attribute_init_invalid: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 *
 * Initialize a PKCS#11 attribute to an 'invalid' or 'not found'
 * state. Specifically this sets the value length to (CK_ULONG)-1
 * as specified in the PKCS#11 specification.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init_invalid (GckAttribute *attr,
                            gulong attr_type)
{
	g_return_if_fail (attr != NULL);
	attr->type = attr_type;
	attr->value = NULL;
	attr->length = G_MAXULONG;
}

/**
 * gck_attribute_init_empty: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 *
 * Initialize a PKCS#11 attribute to an empty state. The attribute
 * type will be set, but no data will be set.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init_empty (GckAttribute *attr, gulong attr_type)
{
	g_return_if_fail (attr != NULL);

	attr->type = attr_type;
	attr->length = 0;
	attr->value = 0;
}

/**
 * gck_attribute_init_boolean: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the boolean value of the attribute
 *
 * Initialize a PKCS#11 attribute to boolean. This will result
 * in a CK_BBOOL attribute from the PKCS#11 specs.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init_boolean (GckAttribute *attr,
                            gulong attr_type,
                            gboolean value)
{
	CK_BBOOL val = value ? CK_TRUE : CK_FALSE;
	g_return_if_fail (attr != NULL);
	gck_attribute_init (attr, attr_type, &val, sizeof (val));
}

/**
 * gck_attribute_init_date: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the date value of the attribute
 *
 * Initialize a PKCS#11 attribute to a date. This will result
 * in a CK_DATE attribute from the PKCS#11 specs.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init_date (GckAttribute *attr,
                         gulong attr_type,
                         const GDate *value)
{
	CK_DATE date;

	g_return_if_fail (attr != NULL);
	g_return_if_fail (value != NULL);

	convert_gdate_to_ckdate (value, &date);
	gck_attribute_init (attr, attr_type, (const guchar *)&date, sizeof (CK_DATE));
}

/**
 * gck_attribute_init_ulong: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the ulong value of the attribute
 *
 * Initialize a PKCS#11 attribute to a unsigned long. This will result
 * in a CK_ULONG attribute from the PKCS#11 specs.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init_ulong (GckAttribute *attr,
                          gulong attr_type,
                          gulong value)
{
	CK_ULONG val = value;
	g_return_if_fail (attr != NULL);
	gck_attribute_init (attr, attr_type, (const guchar *)&val, sizeof (val));
}

/**
 * gck_attribute_init_string: (skip)
 * @attr: an uninitialized attribute
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the null terminated string value of the attribute
 *
 * Initialize a PKCS#11 attribute to a string. This will result
 * in an attribute containing the text, but not the null terminator.
 * The text in the attribute will be of the same encoding as you pass
 * to this function.
 *
 * When done with the attribute you should use [method@Attribute.clear]
 * to free the internal memory.
 **/
void
gck_attribute_init_string (GckAttribute *attr,
                           gulong attr_type,
                           const gchar *value)
{
	g_return_if_fail (attr != NULL);
	gck_attribute_init (attr, attr_type, (const guchar *)value,
	                    value ? strlen (value) : 0);
}

G_DEFINE_BOXED_TYPE (GckAttribute, gck_attribute,
                     gck_attribute_dup, gck_attribute_free)

/**
 * gck_attribute_new:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the raw value of the attribute
 * @length: the length of the attribute
 *
 * Create a new PKCS#11 attribute. The value will be copied
 * into the new attribute.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute
 *          use gck_attribute_free() to free it
 **/
GckAttribute *
gck_attribute_new (gulong attr_type,
                   const guchar *value,
                   gsize length)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init (attr, attr_type, value, length);
	return attr;
}

/**
 * gck_attribute_new_invalid:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 *
 * Create a new PKCS#11 attribute as 'invalid' or 'not found'
 * state. Specifically this sets the value length to (CK_ULONG)-1
 * as specified in the PKCS#11 specification.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute
 *          use gck_attribute_free() to free it
 **/
GckAttribute *
gck_attribute_new_invalid (gulong attr_type)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init_invalid (attr, attr_type);
	return attr;
}

/**
 * gck_attribute_new_empty:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 *
 * Create a new PKCS#11 attribute with empty data.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute
 *          use gck_attribute_free() to free it
 */
GckAttribute *
gck_attribute_new_empty (gulong attr_type)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init_empty (attr, attr_type);
	return attr;
}

/**
 * gck_attribute_new_boolean:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the boolean value of the attribute
 *
 * Initialize a PKCS#11 attribute to boolean. This will result
 * in a CK_BBOOL attribute from the PKCS#11 specs.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute u
 *          gck_attribute_free() to free it
 **/
GckAttribute *
gck_attribute_new_boolean (gulong attr_type,
                           gboolean value)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init_boolean (attr, attr_type, value);
	return attr;
}

/**
 * gck_attribute_new_date:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the date value of the attribute
 *
 * Initialize a PKCS#11 attribute to a date. This will result
 * in a CK_DATE attribute from the PKCS#11 specs.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute u
 *          gck_attribute_free() to free it
 **/
GckAttribute *
gck_attribute_new_date (gulong attr_type,
                        const GDate *value)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init_date (attr, attr_type, value);
	return attr;
}

/**
 * gck_attribute_new_ulong:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the ulong value of the attribute
 *
 * Initialize a PKCS#11 attribute to a unsigned long. This will result
 * in a `CK_ULONG` attribute from the PKCS#11 specs.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute u
 *          gck_attribute_free() to free it
 **/
GckAttribute *
gck_attribute_new_ulong (gulong attr_type,
                         gulong value)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init_ulong (attr, attr_type, value);
	return attr;
}

/**
 * gck_attribute_new_string:
 * @attr_type: the PKCS#11 attribute type to set on the attribute
 * @value: the null-terminated string value of the attribute
 *
 * Initialize a PKCS#11 attribute to a string. This will result
 * in an attribute containing the text, but not the null terminator.
 * The text in the attribute will be of the same encoding as you pass
 * to this function.
 *
 * Returns: (transfer full): the new attribute; when done with the attribute u
 *          gck_attribute_free() to free it
 **/
GckAttribute *
gck_attribute_new_string (gulong attr_type,
                          const gchar *value)
{
	GckAttribute *attr = g_new0 (GckAttribute, 1);
	gck_attribute_init_string (attr, attr_type, value);
	return attr;
}

/**
 * gck_attribute_dup:
 * @attr: the attribute to duplicate
 *
 * Duplicate the PKCS#11 attribute. All value memory is
 * also copied.
 *
 * The @attr must have been allocated or initialized by a Gck function or
 * the results of this function are undefined.
 *
 * Returns: (transfer full): the duplicated attribute; use gck_attribute_free()
 *          to free it
 */
GckAttribute *
gck_attribute_dup (const GckAttribute *attr)
{
	GckAttribute *copy;

	if (!attr)
		return NULL;

	copy = g_new0 (GckAttribute, 1);
	gck_attribute_init_copy (copy, attr);
	return copy;
}

/**
 * gck_attribute_init_copy:
 * @dest: An uninitialized attribute.
 * @src: An attribute to copy.
 *
 * Initialize a PKCS#11 attribute as a copy of another attribute.
 * This copies the value memory as well.
 *
 * When done with the copied attribute you should use
 * [method@Attribute.clear] to free the internal memory.
 */
void
gck_attribute_init_copy (GckAttribute *dest,
                         const GckAttribute *src)
{
	g_return_if_fail (dest != NULL);
	g_return_if_fail (src != NULL);

	dest->type = src->type;
	if (src->length == G_MAXULONG) {
		dest->value = NULL;
		dest->length = G_MAXULONG;
	} else if (src->value == NULL) {
		dest->value = NULL;
		dest->length = 0;
	} else {
		dest->value = value_ref (src->value);
		dest->length = src->length;
	}
}

/**
 * gck_attribute_clear:
 * @attr: Attribute to clear.
 *
 * Clear allocated memory held by a #GckAttribute.
 *
 * This attribute must have been allocated by a Gck library function, or
 * the results of this method are undefined.
 *
 * The type of the attribute will remain set.
 **/
void
gck_attribute_clear (GckAttribute *attr)
{
	g_return_if_fail (attr != NULL);

	if (attr->value != NULL)
		value_unref (attr->value);
	attr->value = NULL;
	attr->length = 0;
}

/**
 * gck_attribute_free:
 * @attr: (type Gck.Attribute): attribute to free
 *
 * Free an attribute and its allocated memory. These is usually
 * used with attributes that are allocated by [ctor@Attribute.new]
 * or a similar function.
 **/
void
gck_attribute_free (gpointer attr)
{
	GckAttribute *a = attr;
	if (attr) {
		gck_attribute_clear (a);
		g_free (a);
	}
}

/**
 * gck_attribute_equal:
 * @attr1: (type Gck.Attribute): first attribute to compare
 * @attr2: (type Gck.Attribute): second attribute to compare
 *
 * Compare two attributes. Useful with <code>GHashTable</code>.
 *
 * Returns: %TRUE if the attributes are equal.
 */
gboolean
gck_attribute_equal (gconstpointer attr1,
                     gconstpointer attr2)
{
	const GckAttribute *aa = attr1;
	const GckAttribute *ab = attr2;

	if (!aa && !ab)
		return TRUE;
	if (!aa || !ab)
		return FALSE;

	if (aa->type != ab->type)
		return FALSE;
	if (aa->length != ab->length)
		return FALSE;
	if (!aa->value && !ab->value)
		return TRUE;
	if (!aa->value || !ab->value)
		return FALSE;
	return memcmp (aa->value, ab->value, aa->length) == 0;
}

/**
 * gck_attribute_hash:
 * @attr: (type Gck.Attribute): attribute to hash
 *
 * Hash an attribute for use in <code>GHashTable</code> keys.
 *
 * Returns: the hash code
 */
guint
gck_attribute_hash (gconstpointer attr)
{
	const GckAttribute *a = attr;
	const signed char *p, *e;
	guint32 h = 5381;

	h ^= _gck_ulong_hash (&a->type);

	if (a->value) {
		for (p = (signed char *)a->value, e = p + a->length; p != e; p++)
			h = (h << 5) + h + *p;
	}

	return h;
}

/**
 * GckAttributes:
 *
 * A set of [struct@Attribute] structures.
 *
 * These attributes contain information about a PKCS11 object. Use
 * [method@Object.get] or [method@Object.set] to set and retrieve attributes on
 * an object.
 */

/**
 * GckAllocator:
 * @data: Memory to allocate or deallocate.
 * @length: New length of memory.
 *
 * An allocator used to allocate data for the attributes in this
 * [struct@Attributes] set.
 *
 * This is a function that acts like g_realloc. Specifically it frees when length is
 * set to zero, it allocates when data is set to %NULL, and it reallocates when both
 * are valid.
 *
 * Returns: The allocated memory, or %NULL when freeing.
 **/

G_DEFINE_BOXED_TYPE (GckAttributes, gck_attributes,
                     gck_attributes_ref, gck_attributes_unref)

/**
 * gck_attributes_new_empty:
 * @first_type: the first empty attribute type
 * @...: the other empty attribute types
 *
 * Creates an GckAttributes array with empty attributes
 *
 * Terminate the argument list with [const@INVALID].
 *
 * Returns: (transfer full): a reference to an empty set of attributes
 **/
GckAttributes *
gck_attributes_new_empty (gulong first_type,
                          ...)
{
	GckBuilder builder = GCK_BUILDER_INIT;
	va_list va;

	va_start (va, first_type);

	while (first_type != GCK_INVALID) {
		gck_builder_add_empty (&builder, first_type);
		first_type = va_arg (va, gulong);
	}

	va_end (va);
	return gck_builder_end (&builder);
}

/**
 * gck_attributes_at:
 * @attrs: The attributes array.
 * @index: The attribute index to retrieve.
 *
 * Get attribute at the specified index in the attribute array.
 *
 * Use [method@Attributes.count] to determine how many attributes are
 * in the array.
 *
 * Returns: (transfer none): the specified attribute
 **/
const GckAttribute *
gck_attributes_at (GckAttributes *attrs,
                   guint index)
{
	g_return_val_if_fail (attrs != NULL, NULL);
	g_return_val_if_fail (index < attrs->count, NULL);
	return attrs->data + index;
}

/**
 * gck_attributes_count:
 * @attrs: The attributes array to count.
 *
 * Get the number of attributes in this attribute array.
 *
 * Return value: The number of contained attributes.
 **/
gulong
gck_attributes_count (GckAttributes *attrs)
{
	g_return_val_if_fail (attrs != NULL, 0);
	return attrs->count;
}

/**
 * gck_attributes_find:
 * @attrs: The attributes array to search.
 * @attr_type: The type of attribute to find.
 *
 * Find an attribute with the specified type in the array.
 *
 * Returns: (transfer none): the first attribute found with the specified type,
 *          or %NULL
 **/
const GckAttribute *
gck_attributes_find (GckAttributes *attrs,
                     gulong attr_type)
{
	g_return_val_if_fail (attrs != NULL, NULL);

	return find_attribute (attrs->data, attrs->count, attr_type);
}

/**
 * gck_attributes_find_boolean:
 * @attrs: The attributes array to search.
 * @attr_type: The type of attribute to find.
 * @value: (out): The resulting gboolean value.
 *
 * Find an attribute with the specified type in the array.
 *
 * The attribute (if found) must be of the right size to store
 * a boolean value (ie: CK_BBOOL). If the attribute is marked invalid
 * then it will be treated as not found.
 *
 * Return value: Whether a value was found or not.
 **/
gboolean
gck_attributes_find_boolean (GckAttributes *attrs, gulong attr_type, gboolean *value)
{
	g_return_val_if_fail (attrs != NULL, FALSE);
	g_return_val_if_fail (value, FALSE);

	return find_attribute_boolean (attrs->data, attrs->count, attr_type, value);
}

/**
 * gck_attributes_find_ulong:
 * @attrs: The attributes array to search.
 * @attr_type: The type of attribute to find.
 * @value: (out): The resulting gulong value.
 *
 * Find an attribute with the specified type in the array.
 *
 * The attribute (if found) must be of the right size to store
 * a unsigned long value (ie: CK_ULONG). If the attribute is marked invalid
 * then it will be treated as not found.
 *
 * Return value: Whether a value was found or not.
 **/
gboolean
gck_attributes_find_ulong (GckAttributes *attrs, gulong attr_type, gulong *value)
{
	g_return_val_if_fail (attrs != NULL, FALSE);
	g_return_val_if_fail (value, FALSE);

	return find_attribute_ulong (attrs->data, attrs->count, attr_type, value);
}

/**
 * gck_attributes_find_string:
 * @attrs: The attributes array to search.
 * @attr_type: The type of attribute to find.
 * @value: (out): The resulting string value.
 *
 * Find an attribute with the specified type in the array.
 *
 * If the attribute is marked invalid then it will be treated as not found.
 * The resulting string will be null-terminated, and must be freed by the caller
 * using g_free().
 *
 * Return value: Whether a value was found or not.
 **/
gboolean
gck_attributes_find_string (GckAttributes *attrs, gulong attr_type, gchar **value)
{
	g_return_val_if_fail (attrs != NULL, FALSE);
	g_return_val_if_fail (value, FALSE);

	return find_attribute_string (attrs->data, attrs->count, attr_type, value);
}

/**
 * gck_attributes_find_date:
 * @attrs: The attributes array to search.
 * @attr_type: The type of attribute to find.
 * @value: (out): The resulting GDate value.
 *
 * Find an attribute with the specified type in the array.
 *
 * The attribute (if found) must be of the right size to store
 * a date value (ie: CK_DATE). If the attribute is marked invalid
 * then it will be treated as not found.
 *
 * Return value: Whether a value was found or not.
 **/
gboolean
gck_attributes_find_date (GckAttributes *attrs, gulong attr_type, GDate *value)
{
	g_return_val_if_fail (attrs != NULL, FALSE);
	g_return_val_if_fail (value, FALSE);

	return find_attribute_date (attrs->data, attrs->count, attr_type, value);
}

/**
 * gck_attributes_ref:
 * @attrs: An attribute array
 *
 * Reference this attributes array.
 *
 * Returns: (transfer full): the attributes
 **/
GckAttributes *
gck_attributes_ref (GckAttributes *attrs)
{
	g_return_val_if_fail (attrs, NULL);
	g_atomic_int_inc (&attrs->refs);
	return attrs;
}

/**
 * gck_attributes_unref:
 * @attrs: (nullable) (type Gck.Attributes) (transfer full): An attribute array
 *
 * Unreference this attribute array.
 *
 * When all outstanding references are gone, the array will be freed.
 */
void
gck_attributes_unref (gpointer attrs)
{
	GckAttributes *attrs_ = attrs;
	const GckAttribute *attr;
	guint i;

	if (!attrs_)
		return;

	if (g_atomic_int_dec_and_test (&attrs_->refs)) {
		for (i = 0; i < attrs_->count; ++i) {
			attr = gck_attributes_at (attrs_, i);
			if (attr->value)
				value_unref (attr->value);
		}
		g_free (attrs_->data);
		g_free (attrs_);
	}
}

/**
 * gck_attributes_contains:
 * @attrs: The attributes to check
 * @match: The attribute to find
 *
 * Check whether the attributes contain a certain attribute.
 *
 * Returns: %TRUE if the attributes contain the attribute.
 */
gboolean
gck_attributes_contains (GckAttributes *attrs,
                         const GckAttribute *match)
{
	const GckAttribute *attr;
	guint i;

	g_return_val_if_fail (attrs != NULL, FALSE);

	for (i = 0; i < attrs->count; ++i) {
		attr = gck_attributes_at (attrs, i);
		if (gck_attribute_equal (attr, match))
			return TRUE;
	}

	return FALSE;
}

CK_ATTRIBUTE_PTR
_gck_builder_prepare_in (GckBuilder *builder,
                         CK_ULONG_PTR n_attrs)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttribute *attr;
	guint i;

	g_return_val_if_fail (builder != NULL, NULL);
	g_return_val_if_fail (n_attrs != NULL, NULL);

	if (real->array == NULL) {
		*n_attrs = 0;
		return NULL;
	}

	/* Prepare the attributes to receive their length */

	for (i = 0; i < real->array->len; ++i) {
		attr = &g_array_index (real->array, GckAttribute, i);
		if (attr->value != NULL) {
			value_unref (attr->value);
			attr->value = NULL;
		}
		attr->length = 0;
	}

	*n_attrs = real->array->len;
	return (CK_ATTRIBUTE_PTR)real->array->data;
}

CK_ATTRIBUTE_PTR
_gck_builder_commit_in (GckBuilder *builder,
                        CK_ULONG_PTR n_attrs)
{
	GckRealBuilder *real = (GckRealBuilder *)builder;
	GckAttribute *attr;
	guint i;

	g_return_val_if_fail (builder != NULL, NULL);
	g_return_val_if_fail (n_attrs != NULL, NULL);

	if (real->array == NULL) {
		*n_attrs = 0;
		return NULL;
	}

	/* Allocate each attribute with the length that was set */

	for (i = 0; i < real->array->len; ++i) {
		attr = &g_array_index (real->array, GckAttribute, i);
		if (attr->length != 0 && attr->length != (gulong)-1)
			attr->value = value_blank (attr->length, real->secure);
		else
			attr->value = NULL;
	}

	*n_attrs = real->array->len;
	return (CK_ATTRIBUTE_PTR)real->array->data;
}

CK_ATTRIBUTE_PTR
_gck_attributes_commit_out (GckAttributes *attrs,
                            CK_ULONG_PTR n_attrs)
{
	g_return_val_if_fail (attrs != NULL, NULL);
	g_return_val_if_fail (n_attrs != NULL, NULL);

	*n_attrs = attrs->count;
	return (CK_ATTRIBUTE_PTR)attrs->data;
}

static gboolean
_gck_attribute_is_ulong_of_type (GckAttribute *attr,
                                 gulong attr_type)
{
	if (attr->type != attr_type)
		return FALSE;
	if (attr->length != sizeof (gulong))
		return FALSE;
	if (!attr->value)
		return FALSE;
	return TRUE;
}

static gboolean
_gck_attribute_is_sensitive (GckAttribute *attr)
{
	/*
	 * Don't print any just attribute, since they may contain
	 * sensitive data
	 */

	switch (attr->type) {
	#define X(x) case x: return FALSE;
	X (CKA_CLASS)
	X (CKA_TOKEN)
	X (CKA_PRIVATE)
	X (CKA_LABEL)
	X (CKA_APPLICATION)
	X (CKA_OBJECT_ID)
	X (CKA_CERTIFICATE_TYPE)
	X (CKA_ISSUER)
	X (CKA_SERIAL_NUMBER)
	X (CKA_AC_ISSUER)
	X (CKA_OWNER)
	X (CKA_ATTR_TYPES)
	X (CKA_TRUSTED)
	X (CKA_CERTIFICATE_CATEGORY)
	X (CKA_JAVA_MIDP_SECURITY_DOMAIN)
	X (CKA_URL)
	X (CKA_HASH_OF_SUBJECT_PUBLIC_KEY)
	X (CKA_HASH_OF_ISSUER_PUBLIC_KEY)
	X (CKA_CHECK_VALUE)
	X (CKA_KEY_TYPE)
	X (CKA_SUBJECT)
	X (CKA_ID)
	X (CKA_SENSITIVE)
	X (CKA_ENCRYPT)
	X (CKA_DECRYPT)
	X (CKA_WRAP)
	X (CKA_UNWRAP)
	X (CKA_SIGN)
	X (CKA_SIGN_RECOVER)
	X (CKA_VERIFY)
	X (CKA_VERIFY_RECOVER)
	X (CKA_DERIVE)
	X (CKA_START_DATE)
	X (CKA_END_DATE)
	X (CKA_MODULUS_BITS)
	X (CKA_PRIME_BITS)
	/* X (CKA_SUBPRIME_BITS) */
	/* X (CKA_SUB_PRIME_BITS) */
	X (CKA_VALUE_BITS)
	X (CKA_VALUE_LEN)
	X (CKA_EXTRACTABLE)
	X (CKA_LOCAL)
	X (CKA_NEVER_EXTRACTABLE)
	X (CKA_ALWAYS_SENSITIVE)
	X (CKA_KEY_GEN_MECHANISM)
	X (CKA_MODIFIABLE)
	X (CKA_SECONDARY_AUTH)
	X (CKA_AUTH_PIN_FLAGS)
	X (CKA_ALWAYS_AUTHENTICATE)
	X (CKA_WRAP_WITH_TRUSTED)
	X (CKA_WRAP_TEMPLATE)
	X (CKA_UNWRAP_TEMPLATE)
	X (CKA_HW_FEATURE_TYPE)
	X (CKA_RESET_ON_INIT)
	X (CKA_HAS_RESET)
	X (CKA_PIXEL_X)
	X (CKA_PIXEL_Y)
	X (CKA_RESOLUTION)
	X (CKA_CHAR_ROWS)
	X (CKA_CHAR_COLUMNS)
	X (CKA_COLOR)
	X (CKA_BITS_PER_PIXEL)
	X (CKA_CHAR_SETS)
	X (CKA_ENCODING_METHODS)
	X (CKA_MIME_TYPES)
	X (CKA_MECHANISM_TYPE)
	X (CKA_REQUIRED_CMS_ATTRIBUTES)
	X (CKA_DEFAULT_CMS_ATTRIBUTES)
	X (CKA_SUPPORTED_CMS_ATTRIBUTES)
	X (CKA_ALLOWED_MECHANISMS)
	X (CKA_X_ASSERTION_TYPE)
	X (CKA_X_CERTIFICATE_VALUE)
	X (CKA_X_PURPOSE)
	X (CKA_X_PEER)
	#undef X
	}

	return TRUE;
}

static void
_gck_format_class (GString *output,
                   CK_OBJECT_CLASS klass)
{
	const gchar *string = NULL;

	switch (klass) {
	#define X(x) case x: string = #x; break;
	X (CKO_DATA)
	X (CKO_CERTIFICATE)
	X (CKO_PUBLIC_KEY)
	X (CKO_PRIVATE_KEY)
	X (CKO_SECRET_KEY)
	X (CKO_HW_FEATURE)
	X (CKO_DOMAIN_PARAMETERS)
	X (CKO_MECHANISM)
	X (CKO_X_TRUST_ASSERTION)
	}

	if (string != NULL)
		g_string_append (output, string);
	else
		g_string_append_printf (output, "0x%08lX", klass);
}

static void
_gck_format_assertion_type (GString *output,
                            CK_X_ASSERTION_TYPE type)
{
	const gchar *string = NULL;

	switch (type) {
	#define X(x) case x: string = #x; break;
	X (CKT_X_UNTRUSTED_CERTIFICATE)
	X (CKT_X_PINNED_CERTIFICATE)
	X (CKT_X_ANCHORED_CERTIFICATE)
	#undef X
	}

	if (string != NULL)
		g_string_append (output, string);
	else
		g_string_append_printf (output, "0x%08lX", type);
}

static void
_gck_format_key_type (GString *output,
                      CK_KEY_TYPE type)
{
	const gchar *string = NULL;

	switch (type) {
	#define X(x) case x: string = #x; break;
	X (CKK_RSA)
	X (CKK_DSA)
	X (CKK_DH)
	/* X (CKK_ECDSA) */
	X (CKK_EC)
	X (CKK_X9_42_DH)
	X (CKK_KEA)
	X (CKK_GENERIC_SECRET)
	X (CKK_RC2)
	X (CKK_RC4)
	X (CKK_DES)
	X (CKK_DES2)
	X (CKK_DES3)
	X (CKK_CAST)
	X (CKK_CAST3)
	X (CKK_CAST128)
	X (CKK_RC5)
	X (CKK_IDEA)
	X (CKK_SKIPJACK)
	X (CKK_BATON)
	X (CKK_JUNIPER)
	X (CKK_CDMF)
	X (CKK_AES)
	X (CKK_BLOWFISH)
	X (CKK_TWOFISH)
	#undef X
	}

	if (string != NULL)
		g_string_append (output, string);
	else
		g_string_append_printf (output, "0x%08lX", type);
}

static void
_gck_format_certificate_type (GString *output,
                              CK_CERTIFICATE_TYPE type)
{
	const gchar *string = NULL;

	switch (type) {
	#define X(x) case x: string = #x; break;
	X (CKC_X_509)
	X (CKC_X_509_ATTR_CERT)
	X (CKC_WTLS)
	}

	if (string != NULL)
		g_string_append (output, string);
	else
		g_string_append_printf (output, "0x%08lX", type);
}

static void
_gck_format_attribute_type (GString *output,
                            gulong type)
{
	const gchar *string = NULL;

	switch (type) {
	#define X(x) case x: string = #x; break;
	X (CKA_CLASS)
	X (CKA_TOKEN)
	X (CKA_PRIVATE)
	X (CKA_LABEL)
	X (CKA_APPLICATION)
	X (CKA_VALUE)
	X (CKA_OBJECT_ID)
	X (CKA_CERTIFICATE_TYPE)
	X (CKA_ISSUER)
	X (CKA_SERIAL_NUMBER)
	X (CKA_AC_ISSUER)
	X (CKA_OWNER)
	X (CKA_ATTR_TYPES)
	X (CKA_TRUSTED)
	X (CKA_CERTIFICATE_CATEGORY)
	X (CKA_JAVA_MIDP_SECURITY_DOMAIN)
	X (CKA_URL)
	X (CKA_HASH_OF_SUBJECT_PUBLIC_KEY)
	X (CKA_HASH_OF_ISSUER_PUBLIC_KEY)
	X (CKA_CHECK_VALUE)
	X (CKA_KEY_TYPE)
	X (CKA_SUBJECT)
	X (CKA_ID)
	X (CKA_SENSITIVE)
	X (CKA_ENCRYPT)
	X (CKA_DECRYPT)
	X (CKA_WRAP)
	X (CKA_UNWRAP)
	X (CKA_SIGN)
	X (CKA_SIGN_RECOVER)
	X (CKA_VERIFY)
	X (CKA_VERIFY_RECOVER)
	X (CKA_DERIVE)
	X (CKA_START_DATE)
	X (CKA_END_DATE)
	X (CKA_MODULUS)
	X (CKA_MODULUS_BITS)
	X (CKA_PUBLIC_EXPONENT)
	X (CKA_PRIVATE_EXPONENT)
	X (CKA_PRIME_1)
	X (CKA_PRIME_2)
	X (CKA_EXPONENT_1)
	X (CKA_EXPONENT_2)
	X (CKA_COEFFICIENT)
	X (CKA_PRIME)
	X (CKA_SUBPRIME)
	X (CKA_BASE)
	X (CKA_PRIME_BITS)
	/* X (CKA_SUBPRIME_BITS) */
	/* X (CKA_SUB_PRIME_BITS) */
	X (CKA_VALUE_BITS)
	X (CKA_VALUE_LEN)
	X (CKA_EXTRACTABLE)
	X (CKA_LOCAL)
	X (CKA_NEVER_EXTRACTABLE)
	X (CKA_ALWAYS_SENSITIVE)
	X (CKA_KEY_GEN_MECHANISM)
	X (CKA_MODIFIABLE)
	X (CKA_ECDSA_PARAMS)
	/* X (CKA_EC_PARAMS) */
	X (CKA_EC_POINT)
	X (CKA_SECONDARY_AUTH)
	X (CKA_AUTH_PIN_FLAGS)
	X (CKA_ALWAYS_AUTHENTICATE)
	X (CKA_WRAP_WITH_TRUSTED)
	X (CKA_WRAP_TEMPLATE)
	X (CKA_UNWRAP_TEMPLATE)
	X (CKA_HW_FEATURE_TYPE)
	X (CKA_RESET_ON_INIT)
	X (CKA_HAS_RESET)
	X (CKA_PIXEL_X)
	X (CKA_PIXEL_Y)
	X (CKA_RESOLUTION)
	X (CKA_CHAR_ROWS)
	X (CKA_CHAR_COLUMNS)
	X (CKA_COLOR)
	X (CKA_BITS_PER_PIXEL)
	X (CKA_CHAR_SETS)
	X (CKA_ENCODING_METHODS)
	X (CKA_MIME_TYPES)
	X (CKA_MECHANISM_TYPE)
	X (CKA_REQUIRED_CMS_ATTRIBUTES)
	X (CKA_DEFAULT_CMS_ATTRIBUTES)
	X (CKA_SUPPORTED_CMS_ATTRIBUTES)
	X (CKA_ALLOWED_MECHANISMS)
	X (CKA_X_ASSERTION_TYPE)
	X (CKA_X_CERTIFICATE_VALUE)
	X (CKA_X_PURPOSE)
	X (CKA_X_PEER)
	#undef X
	}

	if (string != NULL)
		g_string_append (output, string);
	else
		g_string_append_printf (output, "CKA_0x%08lX", type);
}

static void
_gck_format_some_bytes (GString *output,
                        gconstpointer bytes,
                        gulong length)
{
	guchar ch;
	const guchar *data = bytes;
	gulong i;

	if (bytes == NULL) {
		g_string_append (output, "NULL");
		return;
	}

	g_string_append_c (output, '\"');
	for (i = 0; i < length && i < 128; i++) {
		ch = data[i];
		if (ch == '\t')
			g_string_append (output, "\\t");
		else if (ch == '\n')
			g_string_append (output, "\\n");
		else if (ch == '\r')
			g_string_append (output, "\\r");
		else if (ch >= 32 && ch < 127)
			g_string_append_c (output, ch);
		else
			g_string_append_printf (output, "\\x%02x", ch);
	}

	if (i < length)
		g_string_append_printf (output, "...");
	g_string_append_c (output, '\"');
}

static void
_gck_format_attributes (GString *output,
                        GckAttributes *attrs)
{
	GckAttribute *attr;
	guint count, i;

	count = attrs->count;
	g_string_append_printf (output, "(%d) [", count);
	for (i = 0; i < count; i++) {
		attr = attrs->data + i;
		if (i > 0)
			g_string_append_c (output, ',');
		g_string_append (output, " { ");
		_gck_format_attribute_type (output, attr->type);
		g_string_append (output, " = ");
		if (attr->length == GCK_INVALID) {
			g_string_append_printf (output, " (-1) INVALID");
		} else if (_gck_attribute_is_ulong_of_type (attr, CKA_CLASS)) {
			_gck_format_class (output, (CK_OBJECT_CLASS) gck_attribute_get_ulong(attr));
		} else if (_gck_attribute_is_ulong_of_type (attr, CKA_X_ASSERTION_TYPE)) {
			_gck_format_assertion_type (output, (CK_X_ASSERTION_TYPE) gck_attribute_get_ulong(attr));
		} else if (_gck_attribute_is_ulong_of_type (attr, CKA_CERTIFICATE_TYPE)) {
			_gck_format_certificate_type (output, (CK_CERTIFICATE_TYPE) gck_attribute_get_ulong(attr));
		} else if (_gck_attribute_is_ulong_of_type (attr, CKA_KEY_TYPE)) {
			_gck_format_key_type (output, (CK_KEY_TYPE) gck_attribute_get_ulong(attr));
		} else if (_gck_attribute_is_sensitive (attr)) {
			g_string_append_printf (output, " (%lu) NOT-PRINTED", attr->length);
		} else {
			g_string_append_printf (output, " (%lu) ", attr->length);
			_gck_format_some_bytes (output, attr->value, attr->length);
		}
		g_string_append (output, " }");
	}
	g_string_append (output, " ]");
}

/**
 * gck_attributes_to_string:
 * @attrs: the attributes
 *
 * Print out attributes to a string in aform that's useful for debugging
 * or logging.
 *
 * The format of the string returned may change in the future.
 *
 * Returns: a newly allocated string
 */
gchar *
gck_attributes_to_string (GckAttributes *attrs)
{
	GString *output = g_string_sized_new (128);
	_gck_format_attributes (output, attrs);
	return g_string_free (output, FALSE);
}

/**
 * gck_attributes_new:
 *
 * Create a new empty `GckAttributes` array.
 *
 * Returns: (transfer full): a reference to the new attributes array;
 *          when done with the array release it with gck_attributes_unref().
 **/
GckAttributes *
gck_attributes_new (void)
{
	GckBuilder builder = GCK_BUILDER_INIT;
	return gck_builder_end (&builder);
}