aboutsummaryrefslogtreecommitdiffstats
path: root/SoftHSMv2/src/lib/object_store/DBObject.cpp
blob: d2515bde068b292a01da881522998bede09a8bf9 (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
/*
 * Copyright (c) 2013 SURFnet bv
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*****************************************************************************
 DBObject.h

 This class represents object records in a database
 *****************************************************************************/

#include "config.h"
#include "DBObject.h"
#include "OSPathSep.h"
#include "DB.h"
#include "OSAttributes.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <cstdio>
#include <map>

// Create an object that can access a record, but don't do anything yet.
DBObject::DBObject(DB::Connection *connection, ObjectStoreToken *token)
	: _mutex(MutexFactory::i()->getMutex()), _connection(connection), _token(token), _objectId(0), _transaction(NULL)
{

}

DBObject::DBObject(DB::Connection *connection, ObjectStoreToken *token, long long objectId)
	: _mutex(MutexFactory::i()->getMutex()), _connection(connection), _token(token), _objectId(objectId), _transaction(NULL)
{
}

// Destructor
DBObject::~DBObject()
{
	for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it = _attributes.begin(); it!=_attributes.end(); ++it) {
		delete it->second;
		it->second = NULL;
	}
	if (_transaction)
	{
		for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it = _transaction->begin(); it!=_transaction->end(); ++it) {
			delete it->second;
			it->second = NULL;
		}
		delete _transaction;
	}
	MutexFactory::i()->recycleMutex(_mutex);
}

void DBObject::dropConnection()
{
	MutexLocker lock(_mutex);

	_connection = NULL;
}

// create tables to support storage of attributes for the DBObject
bool DBObject::createTables()
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	// Create the tables inside the database
	DB::Statement cr_object = _connection->prepare("create table object (id integer primary key autoincrement);");
	if (!_connection->execute(cr_object))
	{
		ERROR_MSG("Failed to create \"object\" table");
		return false;
	}

	// attribute_text
	DB::Statement cr_attr_text = _connection->prepare(
		"create table attribute_text ("
		"value text,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_text))
	{
		ERROR_MSG("Failed to create \"attribute_text\" table");
		return false;
	}

	// attribute_integer
	DB::Statement cr_attr_integer = _connection->prepare(
		"create table attribute_integer ("
		"value integer,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_integer))
	{
		ERROR_MSG("Failed to create \"attribute_integer\" table");
		return false;
	}

	// attribute_binary
	DB::Statement cr_attr_binary = _connection->prepare(
		"create table attribute_binary ("
		"value blob,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_binary))
	{
		ERROR_MSG("Failed to create \"attribute_binary\" table");
		return false;
	}

	// attribute_array
	DB::Statement cr_attr_array = _connection->prepare(
		"create table attribute_array ("
		"value blob,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_array))
	{
		ERROR_MSG("Failed to create \"attribute_array\" table");
		return false;
	}

	// attribute_boolean
	DB::Statement cr_attr_boolean = _connection->prepare(
		"create table attribute_boolean ("
		"value boolean,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_boolean))
	{
		ERROR_MSG("Failed to create \"attribute_boolean\" table");
		return false;
	}

	// attribute_datetime
	DB::Statement cr_attr_datetime = _connection->prepare(
		"create table attribute_datetime ("
		"value datetime,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_datetime))
	{
		ERROR_MSG("Failed to create \"attribute_datetime\" table");
		return false;
	}

	// attribute_real
	DB::Statement cr_attr_real = _connection->prepare(
		"create table attribute_real ("
		"value real,"
		"type integer,"
		"object_id integer references object(id) on delete cascade,"
		"id integer primary key autoincrement)"
		);
	if (!_connection->execute(cr_attr_real))
	{
		ERROR_MSG("Failed to create \"attribute_real\" table");
		return false;
	}

	return true;
}

bool DBObject::dropTables()
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	// Create the tables inside the database
	DB::Statement dr_object = _connection->prepare("drop table object");
	if (!_connection->execute(dr_object))
	{
		ERROR_MSG("Failed to drop \"object\" table");
		return false;
	}

	// attribute_text
	DB::Statement dr_attr_text = _connection->prepare("drop table attribute_text");
	if (!_connection->execute(dr_attr_text))
	{
		ERROR_MSG("Failed to drop \"attribute_text\" table");
		return false;
	}

	// attribute_integer
	DB::Statement dr_attr_integer = _connection->prepare("drop table attribute_integer");
	if (!_connection->execute(dr_attr_integer))
	{
		ERROR_MSG("Failed to drop \"attribute_integer\" table");
		return false;
	}

	// attribute_binary
	DB::Statement dr_attr_binary = _connection->prepare("drop table attribute_binary");
	if (!_connection->execute(dr_attr_binary))
	{
		ERROR_MSG("Failed to drop \"attribute_binary\" table");
		return false;
	}

	// attribute_array
	DB::Statement dr_attr_array = _connection->prepare("drop table attribute_array");
	if (!_connection->execute(dr_attr_array))
	{
		ERROR_MSG("Failed to drop \"attribute_array\" table");
		return false;
	}

	// attribute_boolean
	DB::Statement dr_attr_boolean = _connection->prepare("drop table attribute_boolean");
	if (!_connection->execute(dr_attr_boolean))
	{
		ERROR_MSG("Failed to drop \"attribute_boolean\" table");
		return false;
	}

	// attribute_datetime
	DB::Statement dr_attr_datetime = _connection->prepare("drop table attribute_datetime");
	if (!_connection->execute(dr_attr_datetime))
	{
		ERROR_MSG("Failed to drop \"attribute_datetime\" table");
		return false;
	}

	// attribute_real
	DB::Statement dr_attr_real = _connection->prepare("drop table attribute_real");
	if (!_connection->execute(dr_attr_real))
	{
		ERROR_MSG("Failed to drop \"attribute_real\" table");
		return false;
	}

	return true;
}

bool DBObject::find(long long objectId)
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	if (objectId == 0) {
		ERROR_MSG("Invalid object_id 0 passed to find");
		return false;
	}

	// find the object in the database for the given object_id
	DB::Statement statement = _connection->prepare(
				"select id from object where id=%lld",
				objectId);
	if (!statement.isValid()) {
		ERROR_MSG("Preparing object selection statement failed");
		return false;
	}

	DB::Result result = _connection->perform(statement);
	if (result.getLongLong(1) != objectId) {
		ERROR_MSG("Failed to find object with id %lld",objectId);
		return false;
	}

	_objectId = objectId;
	return true;
}

bool DBObject::insert()
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	DB::Statement statement = _connection->prepare("insert into object default values");

	if (!_connection->execute(statement)) {
		ERROR_MSG("Failed to insert a new object");
		return false;
	}

	_objectId = _connection->lastInsertRowId();
	return _objectId != 0;
}

bool DBObject::remove()
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	DB::Statement statement = _connection->prepare("delete from object where id=%lld",_objectId);

	if (!_connection->execute(statement)) {
		ERROR_MSG("Failed to remove an existing object");
		return false;
	}

	_objectId = 0;
	return true;
}

long long DBObject::objectId()
{
	MutexLocker lock(_mutex);

	return _objectId;
}

static bool isModifiable(CK_ATTRIBUTE_TYPE type)
{
	switch (type) {
	case CKA_LABEL:
	case CKA_TRUSTED:
	case CKA_ID:
	case CKA_ISSUER:
	case CKA_SERIAL_NUMBER:
	case CKA_START_DATE:
	case CKA_END_DATE:
	case CKA_DERIVE:
	case CKA_SUBJECT:
	case CKA_ENCRYPT:
	case CKA_VERIFY:
	case CKA_VERIFY_RECOVER:
	case CKA_WRAP:
	case CKA_SENSITIVE:
	case CKA_DECRYPT:
	case CKA_SIGN:
	case CKA_SIGN_RECOVER:
	case CKA_UNWRAP:
	case CKA_EXTRACTABLE:
	case CKA_OS_TOKENFLAGS:
	case CKA_OS_SOPIN:
	case CKA_OS_USERPIN:
		return true;
	default:
		return false;
	}
}

enum AttributeKind {
	akUnknown,
	akBoolean,
	akInteger,
	akBinary,
	akAttrMap,
	akMechSet
};

static AttributeKind attributeKind(CK_ATTRIBUTE_TYPE type)
{
	switch (type) {
	case CKA_CLASS: return akInteger;
	case CKA_TOKEN: return akBoolean;
	case CKA_PRIVATE: return akBoolean;
	case CKA_LABEL: return akBinary;
	case CKA_APPLICATION: return akBinary;
	case CKA_VALUE: return akBinary;
	case CKA_OBJECT_ID: return akBinary;
	case CKA_CERTIFICATE_TYPE: return akInteger;
	case CKA_ISSUER: return akBinary;
	case CKA_SERIAL_NUMBER: return akBinary;
	case CKA_AC_ISSUER: return akBinary;
	case CKA_OWNER: return akBinary;
	case CKA_ATTR_TYPES: return akBinary;
	case CKA_TRUSTED: return akBoolean;
	case CKA_CERTIFICATE_CATEGORY: return akInteger;
	case CKA_JAVA_MIDP_SECURITY_DOMAIN: return akInteger;
	case CKA_URL: return akBinary;
	case CKA_HASH_OF_SUBJECT_PUBLIC_KEY: return akBinary;
	case CKA_HASH_OF_ISSUER_PUBLIC_KEY: return akBinary;
	case CKA_NAME_HASH_ALGORITHM: return akInteger;
	case CKA_CHECK_VALUE: return akBinary;
	case CKA_KEY_TYPE: return akInteger;
	case CKA_SUBJECT: return akBinary;
	case CKA_ID: return akBinary;
	case CKA_SENSITIVE: return akBoolean;
	case CKA_ENCRYPT: return akBoolean;
	case CKA_DECRYPT: return akBoolean;
	case CKA_WRAP: return akBoolean;
	case CKA_UNWRAP: return akBoolean;
	case CKA_SIGN: return akBoolean;
	case CKA_SIGN_RECOVER: return akBoolean;
	case CKA_VERIFY: return akBoolean;
	case CKA_VERIFY_RECOVER: return akBoolean;
	case CKA_DERIVE: return akBoolean;
	case CKA_START_DATE: return akBinary;
	case CKA_END_DATE: return akBinary;
	case CKA_MODULUS: return akBinary;
	case CKA_MODULUS_BITS: return akInteger;
	case CKA_PUBLIC_EXPONENT: return akBinary;
	case CKA_PRIVATE_EXPONENT: return akBinary;
	case CKA_PRIME_1: return akBinary;
	case CKA_PRIME_2: return akBinary;
	case CKA_EXPONENT_1: return akBinary;
	case CKA_EXPONENT_2: return akBinary;
	case CKA_COEFFICIENT: return akBinary;
	case CKA_PRIME: return akBinary;
	case CKA_SUBPRIME: return akBinary;
	case CKA_BASE: return akBinary;
	case CKA_PRIME_BITS: return akInteger;
	case CKA_SUBPRIME_BITS: return akInteger;
	case CKA_VALUE_BITS: return akInteger;
	case CKA_VALUE_LEN: return akInteger;
	case CKA_EXTRACTABLE: return akBoolean;
	case CKA_LOCAL: return akBoolean;
	case CKA_NEVER_EXTRACTABLE: return akBoolean;
	case CKA_ALWAYS_SENSITIVE: return akBoolean;
	case CKA_KEY_GEN_MECHANISM: return akInteger;
	case CKA_MODIFIABLE: return akBoolean;
	case CKA_COPYABLE: return akBoolean;
	case CKA_ECDSA_PARAMS: return akBinary;
	case CKA_EC_POINT: return akBinary;
	case CKA_SECONDARY_AUTH: return akBoolean;
	case CKA_AUTH_PIN_FLAGS: return akInteger;
	case CKA_ALWAYS_AUTHENTICATE: return akBoolean;
	case CKA_WRAP_WITH_TRUSTED: return akBoolean;
/*
	case CKA_OTP_FORMAT:
	case CKA_OTP_LENGTH:
	case CKA_OTP_TIME_INTERVAL:
	case CKA_OTP_USER_FRIENDLY_MODE:
	case CKA_OTP_CHALLENGE_REQUIREMENT:
	case CKA_OTP_TIME_REQUIREMENT:
	case CKA_OTP_COUNTER_REQUIREMENT:
	case CKA_OTP_PIN_REQUIREMENT:
	case CKA_OTP_COUNTER:
	case CKA_OTP_TIME:
	case CKA_OTP_USER_IDENTIFIER:
	case CKA_OTP_SERVICE_IDENTIFIER:
	case CKA_OTP_SERVICE_LOGO:
	case CKA_OTP_SERVICE_LOGO_TYPE:
*/
	case CKA_GOSTR3410_PARAMS: return akBinary;
	case CKA_GOSTR3411_PARAMS: return akBinary;
	case CKA_GOST28147_PARAMS: return akBinary;
/*
	case CKA_HW_FEATURE_TYPE:
	case CKA_RESET_ON_INIT:
	case CKA_HAS_RESET:
	case CKA_PIXEL_X:
	case CKA_PIXEL_Y:
	case CKA_RESOLUTION:
	case CKA_CHAR_ROWS:
	case CKA_CHAR_COLUMNS:
	case CKA_COLOR:
	case CKA_BITS_PER_PIXEL:
	case CKA_CHAR_SETS:
	case CKA_ENCODING_METHODS:
	case CKA_MIME_TYPES:
	case CKA_MECHANISM_TYPE:
	case CKA_REQUIRED_CMS_ATTRIBUTES:
	case CKA_DEFAULT_CMS_ATTRIBUTES:
	case CKA_SUPPORTED_CMS_ATTRIBUTES:
*/
	case CKA_WRAP_TEMPLATE: return akAttrMap;
	case CKA_UNWRAP_TEMPLATE: return akAttrMap;
	case CKA_DERIVE_TEMPLATE: return akAttrMap;
	case CKA_ALLOWED_MECHANISMS: return akMechSet;

	case CKA_OS_TOKENLABEL: return akBinary;
	case CKA_OS_TOKENSERIAL: return akBinary;
	case CKA_OS_TOKENFLAGS: return akInteger;
	case CKA_OS_SOPIN: return akBinary;
	case CKA_OS_USERPIN: return akBinary;

	default: return akUnknown;
	}
}

static bool decodeMechanismTypeSet(std::set<CK_MECHANISM_TYPE>& set, const unsigned char *binary, size_t size)
{
	for (size_t pos = 0; pos < size; )
	{
		// finished?
		if (pos == size) break;

		CK_MECHANISM_TYPE mechType;
		if (pos + sizeof(mechType) > size)
		{
			ERROR_MSG("mechanism type set overrun");
			return false;
		}

		memcpy(&mechType, binary + pos, sizeof(mechType));
		pos += sizeof(mechType);

		set.insert(mechType);
    }

	return true;
}

static void encodeMechanismTypeSet(ByteString& value, const std::set<CK_MECHANISM_TYPE>& set)
{
	for (std::set<CK_MECHANISM_TYPE>::const_iterator i = set.begin(); i != set.end(); ++i)
	{
		CK_MECHANISM_TYPE mechType = *i;
		value += ByteString((unsigned char *) &mechType, sizeof(mechType));
	}
}

static bool decodeAttributeMap(std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& map, const unsigned char *binary, size_t size)
{
	for (size_t pos = 0; pos < size; )
	{
		// finished?
		if (pos == size) break;

		CK_ATTRIBUTE_TYPE attrType;
		if (pos + sizeof(attrType) > size)
		{
			goto overrun;
		}
		memcpy(&attrType, binary + pos, sizeof(attrType));
		pos += sizeof(attrType);

		AttributeKind attrKind;
		if (pos + sizeof(AttributeKind) > size)
		{
			goto overrun;
		}
		memcpy(&attrKind, binary + pos, sizeof(attrKind));
		pos += sizeof(attrKind);

		// Verify using attributeKind()?

		switch (attrKind)
		{
			case akBoolean:
			{
				bool value;
				if (pos + sizeof(value) > size)
				{
					goto overrun;
				}
				memcpy(&value, binary + pos, sizeof(value));
				pos += sizeof(value);

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			case akInteger:
			{
				unsigned long value;
				if (pos + sizeof(value) > size)
				{
					goto overrun;
				}
				memcpy(&value, binary + pos, sizeof(value));
				pos += sizeof(value);

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			case akBinary:
			{
				ByteString value;
				unsigned long len;
				if (pos + sizeof(len) > size)
				{
					goto overrun;
				}
				memcpy(&len, binary + pos, sizeof(len));
				pos += sizeof(len);

				if (pos + len > size)
				{
					goto overrun;
				}
				value.resize(len);
				memcpy(&value[0], binary + pos, len);
				pos += len;

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			case akMechSet:
			{
				unsigned long len;
				if (pos + sizeof(len) > size)
				{
					goto overrun;
				}
				memcpy(&len, binary + pos, sizeof(len));
				pos += sizeof(len);

				if (pos + len > size)
				{
					goto overrun;
				}

				std::set<CK_MECHANISM_TYPE> value;
				if (!decodeMechanismTypeSet(value, binary + pos, len)) {
					return false;
				}
				pos += len;

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			default:
			ERROR_MSG("unsupported attribute kind in attribute map");

			return false;
		}
	}

	return true;

overrun:
	ERROR_MSG("attribute map template overrun");

	return false;
}

static bool encodeAttributeMap(ByteString& value, const std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& attributes)
{
	for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute>::const_iterator i = attributes.begin(); i != attributes.end(); ++i)
	{
		CK_ATTRIBUTE_TYPE attrType = i->first;
		value += ByteString((unsigned char*) &attrType, sizeof(attrType));

		OSAttribute attr = i->second;
		if (attr.isBooleanAttribute())
		{
			AttributeKind attrKind = akBoolean;
			value += ByteString((unsigned char*) &attrKind, sizeof(attrKind));

			bool val = attr.getBooleanValue();
			value += ByteString((unsigned char*) &val, sizeof(val));
		}
		else if (attr.isUnsignedLongAttribute())
		{
			AttributeKind attrKind = akInteger;
			value += ByteString((unsigned char*) &attrKind, sizeof(attrKind));

			unsigned long val = attr.getUnsignedLongValue();
			value += ByteString((unsigned char*) &val, sizeof(val));
		}
		else if (attr.isByteStringAttribute())
		{
			AttributeKind attrKind = akBinary;
			value += ByteString((unsigned char*) &attrKind, sizeof(attrKind));

			ByteString val = attr.getByteStringValue();
			unsigned long len = val.size();
			value += ByteString((unsigned char*) &len, sizeof(len));
			value += val;
		}
		else if (attr.isMechanismTypeSetAttribute())
		{
			AttributeKind attrKind = akMechSet;
			value += ByteString((unsigned char*) &attrKind, sizeof(attrKind));

			ByteString val;
			encodeMechanismTypeSet(val, attr.getMechanismTypeSetValue());

			unsigned long len = val.size();
			value += ByteString((unsigned char*) &len, sizeof(len));
			value += val;
		}
		else
		{
			ERROR_MSG("unsupported attribute kind for attribute map");

			return false;
		}
	}

	return true;
}

OSAttribute *DBObject::accessAttribute(CK_ATTRIBUTE_TYPE type)
{
	switch (attributeKind(type))
	{
		case akUnknown:
			return NULL;
		case akBoolean:
		{
			// try to find the attribute in the boolean attribute table
			DB::Statement statement = _connection->prepare(
				"select value from attribute_boolean where type=%lu and object_id=%lld",
				type,
				_objectId);
			if (!statement.isValid())
			{
				return NULL;
			}
			DB::Result result = _connection->perform(statement);
			if (!result.isValid())
			{
				return NULL;
			}
			// Store the attribute in the transaction when it is active.
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*> *attrs = &_attributes;
			if (_transaction)
				attrs = _transaction;

			bool value = result.getInt(1) != 0;
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 attrs->find(type);
			OSAttribute *attr;
			if (it != attrs->end())
			{
				if (it->second != NULL)
				{
					delete it->second;
				}

				it->second = new OSAttribute(value);
				attr = it->second;
			}
			else
			{
				attr = new OSAttribute(value);
				(*attrs)[type] = attr;
			}
			return attr;
		}
		case akInteger:
		{
			// try to find the attribute in the integer attribute table
			DB::Statement statement = _connection->prepare(
				"select value from attribute_integer where type=%lu and object_id=%lld",
				type,
				_objectId);
			if (!statement.isValid())
			{
				return NULL;
			}
			DB::Result result = _connection->perform(statement);
			if (!result.isValid())
			{
				return NULL;
			}
			// Store the attribute in the transaction when it is active.
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*> *attrs = &_attributes;
			if (_transaction)
				attrs = _transaction;

			unsigned long value = result.getULongLong(1);
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 attrs->find(type);
			OSAttribute *attr;
			if (it != attrs->end())
			{
				if (it->second != NULL)
				{
					delete it->second;
				}

				it->second = new OSAttribute(value);
				attr = it->second;
			}
			else
			{
				attr = new OSAttribute(value);
				(*attrs)[type] = attr;
			}
			return attr;
		}
		case akBinary:
		{
			// try to find the attribute in the binary attribute table
			DB::Statement statement = _connection->prepare(
				"select value from attribute_binary where type=%lu and object_id=%lld",
				type,
				_objectId);
			if (!statement.isValid())
			{
				return NULL;
			}
			DB::Result result = _connection->perform(statement);
			if (!result.isValid())
			{
				return NULL;
			}
			// Store the attribute in the transaction when it is active.
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*> *attrs = &_attributes;
			if (_transaction)
				attrs = _transaction;

			const unsigned char *value = result.getBinary(1);
			size_t size = result.getFieldLength(1);
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 attrs->find(type);
			OSAttribute *attr;
			if (it != attrs->end())
			{
				if (it->second != NULL)
				{
					delete it->second;
				}

				it->second = new OSAttribute(ByteString(value,size));
				attr = it->second;
			}
			else
			{
				attr = new OSAttribute(ByteString(value,size));
				(*attrs)[type] = attr;
				return attr;
			}
			return attr;
		}
		case akMechSet:
		{
			// try to find the attribute in the binary attribute table
			DB::Statement statement = _connection->prepare(
					"select value from attribute_binary where type=%lu and object_id=%lld",
					type,
					_objectId);
			if (!statement.isValid())
			{
				return NULL;
			}
			DB::Result result = _connection->perform(statement);
			if (!result.isValid())
			{
				return NULL;
			}
			// Store the attribute in the transaction when it is active.
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*> *attrs = &_attributes;
			if (_transaction)
				attrs = _transaction;

			const unsigned char *value = result.getBinary(1);
			size_t size = result.getFieldLength(1);

			std::set<CK_MECHANISM_TYPE> set;
			if (!decodeMechanismTypeSet(set, value, size))
			{
				return NULL;
			}

			OSAttribute *attr;
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 attrs->find(type);
			if (it != attrs->end())
			{
				if (it->second != NULL)
				{
					delete it->second;
				}

				it->second = new OSAttribute(set);
				attr = it->second;
			}
			else
			{
				attr = new OSAttribute(set);
				(*attrs)[type] = attr;
				return attr;
			}
			return attr;
		}
		case akAttrMap:
		{
			// try to find the attribute in the array attribute table
			DB::Statement statement = _connection->prepare(
				"select value from attribute_array where type=%lu and object_id=%lld",
				type,
				_objectId);
			if (!statement.isValid())
			{
				return NULL;
			}
			DB::Result result = _connection->perform(statement);
			if (!result.isValid())
			{
				return NULL;
			}
			// Store the attribute in the transaction when it is active.
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*> *attrs = &_attributes;
			if (_transaction)
				attrs = _transaction;

			const unsigned char *binary = result.getBinary(1);
			size_t size = result.getFieldLength(1);
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 attrs->find(type);
			OSAttribute *attr;
			if (it != attrs->end())
			{
				std::map<CK_ATTRIBUTE_TYPE,OSAttribute> value;
				if (!decodeAttributeMap(value,binary,size))
				{
					return NULL;
				}

				if (it->second != NULL)
				{
					delete it->second;
				}

				it->second = new OSAttribute(value);
				attr = it->second;
			}
			else
			{
				std::map<CK_ATTRIBUTE_TYPE,OSAttribute> value;
				if (!decodeAttributeMap(value,binary,size))
				{
					return NULL;
				}
				attr = new OSAttribute(value);
				(*attrs)[type] = attr;
				return attr;
			}
			return attr;
		}
	}

	return NULL;
}

// Retrieve the specified attribute for internal use
// Calling function must lock the mutex
OSAttribute* DBObject::getAttributeDB(CK_ATTRIBUTE_TYPE type)
{
	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return NULL;
	}

	if (_objectId == 0)
	{
		ERROR_MSG("Cannot read from invalid object.");
		return NULL;
	}

	// If a transaction is in progress, we can just return the attribute from the transaction.
	if (_transaction)
	{
		std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 _transaction->find(type);
		if (it != _transaction->end())
			return it->second;
	}

	// If the attribute exists and is non-modifiable then return a previously retrieved attribute value.
	if (!isModifiable(type))
	{
		std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 _attributes.find(type);
		if (it != _attributes.end())
		{
			return it->second;
		}
	}

	return accessAttribute(type);
}

// Check if the specified attribute exists
bool DBObject::attributeExists(CK_ATTRIBUTE_TYPE type)
{
	MutexLocker lock(_mutex);

	return getAttributeDB(type) != NULL;
}

// Retrieve the specified attribute
OSAttribute DBObject::getAttribute(CK_ATTRIBUTE_TYPE type)
{
	MutexLocker lock(_mutex);

	OSAttribute* attr = getAttributeDB(type);
	if (attr == NULL) return OSAttribute((unsigned long)0);

	return *attr;
}

bool DBObject::getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val)
{
	MutexLocker lock(_mutex);

	OSAttribute* attr = getAttributeDB(type);
	if (attr == NULL) return val;

	if (attr->isBooleanAttribute())
	{
		return attr->getBooleanValue();
	}
	else
	{
		ERROR_MSG("The attribute is not a boolean: 0x%08X", type);
		return val;
	}
}

unsigned long DBObject::getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val)
{
	MutexLocker lock(_mutex);

	OSAttribute* attr = getAttributeDB(type);
	if (attr == NULL) return val;

	if (attr->isUnsignedLongAttribute())
	{
		return attr->getUnsignedLongValue();
	}
	else
	{
		ERROR_MSG("The attribute is not an unsigned long: 0x%08X", type);
		return val;
	}
}

ByteString DBObject::getByteStringValue(CK_ATTRIBUTE_TYPE type)
{
	MutexLocker lock(_mutex);

	ByteString val;

	OSAttribute* attr = getAttributeDB(type);
	if (attr == NULL) return val;

	if (attr->isByteStringAttribute())
	{
		return attr->getByteStringValue();
	}
	else
	{
		ERROR_MSG("The attribute is not a byte string: 0x%08X", type);
		return val;
	}
}

CK_ATTRIBUTE_TYPE DBObject::nextAttributeType(CK_ATTRIBUTE_TYPE)
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}
	if (_objectId == 0)
	{
		ERROR_MSG("Cannot get next attribute for invalid object.");
		return false;
	}

	// FIXME: implement for C_CopyObject
	return CKA_CLASS;
}

// Set the specified attribute
bool DBObject::setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute)
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}
	if (_objectId == 0)
	{
		ERROR_MSG("Cannot update invalid object.");
		return false;
	}

	// Retrieve and existing attribute if it exists or NULL if it doesn't
	OSAttribute *attr = getAttributeDB(type);

	// Update an existing attribute...
	if (attr)
	{
		DB::Statement statement;
		if (attr->isBooleanAttribute())
		{
			// update boolean attribute
			statement = _connection->prepare(
					"update attribute_boolean set value=%d where type=%lu and object_id=%lld",
					attribute.getBooleanValue() ? 1 : 0,
					type,
					_objectId);
		}
		else if (attr->isUnsignedLongAttribute())
		{
			// update integer attribute
			statement = _connection->prepare(
					"update attribute_integer set value=%lld where type=%lu and object_id=%lld",
					static_cast<long long>(attribute.getUnsignedLongValue()),
					type,
					_objectId);
		}
		else if (attr->isByteStringAttribute())
		{
			// update binary attribute
			statement = _connection->prepare(
					"update attribute_binary set value=? where type=%lu and object_id=%lld",
					type,
					_objectId);
			DB::Bindings(statement).bindBlob(1, attribute.getByteStringValue().const_byte_str(), attribute.getByteStringValue().size(), SQLITE_STATIC);
		}
		else if (attr->isMechanismTypeSetAttribute())
		{
			// update binary attribute
			ByteString value;
			encodeMechanismTypeSet(value, attribute.getMechanismTypeSetValue());

			statement = _connection->prepare(
					"update attribute_binary set value=? where type=%lu and object_id=%lld",
					type,
					_objectId);
			DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
		}
		else if (attr->isAttributeMapAttribute())
		{
			// update attribute map attribute
			ByteString value;
			if (!encodeAttributeMap(value, attribute.getAttributeMapValue()))
			{
				return false;
			}

			statement = _connection->prepare(
					"update attribute_array set value=? where type=%lu and object_id=%lld",
					type,
					_objectId);
			DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
		}

		// Statement is valid when a prepared statement has been attached to it.
		if (statement.isValid())
		{
			if (!_connection->execute(statement))
			{
				ERROR_MSG("Failed to update attribute %lu for object %lld",type,_objectId);
				return false;
			}

			if (_transaction)
			{
				std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 _transaction->find(type);
				if (it != _transaction->end())
					*it->second = attribute;
				else
					(*_transaction)[type] = new OSAttribute(attribute);
			} else
				*attr = attribute;
			return true;
		}
	}

	DB::Statement statement;

	// Insert the attribute, because it is currently unknown
	if (attribute.isBooleanAttribute())
	{
		// Could not update it, so we need to insert it.
		statement = _connection->prepare(
					"insert into attribute_boolean (value,type,object_id) values (%d,%lu,%lld)",
					attribute.getBooleanValue() ? 1 : 0,
					type,
					_objectId);

	}
	else if (attribute.isUnsignedLongAttribute())
	{
		// Could not update it, so we need to insert it.
		statement = _connection->prepare(
					"insert into attribute_integer (value,type,object_id) values (%lld,%lu,%lld)",
					static_cast<long long>(attribute.getUnsignedLongValue()),
					type,
					_objectId);
	}
	else if (attribute.isByteStringAttribute())
	{
		// Could not update it, so we need to insert it.
		statement = _connection->prepare(
					"insert into attribute_binary (value,type,object_id) values (?,%lu,%lld)",
					type,
					_objectId);

		DB::Bindings(statement).bindBlob(1, attribute.getByteStringValue().const_byte_str(), attribute.getByteStringValue().size(), SQLITE_STATIC);
	}
	else if (attribute.isMechanismTypeSetAttribute())
	{
		// Could not update it, so we need to insert it.
		ByteString value;
		encodeMechanismTypeSet(value, attribute.getMechanismTypeSetValue());

		statement = _connection->prepare(
				"insert into attribute_binary (value,type,object_id) values (?,%lu,%lld)",
				type,
				_objectId);
		DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
	}
	else if (attribute.isAttributeMapAttribute())
	{
		// Could not update it, so we need to insert it.
		ByteString value;
		if (!encodeAttributeMap(value, attribute.getAttributeMapValue()))
		{
			return false;
		}

		statement = _connection->prepare(
				"insert into attribute_array (value,type,object_id) values (?,%lu,%lld)",
				type,
				_objectId);
		DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
	}

	// Statement is valid when a prepared statement has been attached to it.
	if (statement.isValid())
	{
		if (!_connection->execute(statement))
		{
			ERROR_MSG("Failed to insert attribute %lu for object %lld",type,_objectId);
			return false;
		}

		if (_transaction)
			(*_transaction)[type] = new OSAttribute(attribute);
		else
			_attributes[type] = new OSAttribute(attribute);
		return true;
	}

	return false;
}

// Set the specified attribute
bool DBObject::deleteAttribute(CK_ATTRIBUTE_TYPE type)
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}
	if (_objectId == 0)
	{
		ERROR_MSG("Cannot update invalid object.");
		return false;
	}

	// Retrieve and existing attribute if it exists or NULL if it doesn't
	OSAttribute *attr = getAttributeDB(type);
	if (attr == NULL)
	{
		ERROR_MSG("Cannot delete an attribute that doesn't exist.");
		return false;
	}

	DB::Statement statement;
	if (attr->isBooleanAttribute())
	{
		// delete boolean attribute
		statement = _connection->prepare(
				"delete from attribute_boolean where type=%lu and object_id=%lld",
				type,
				_objectId);
	}
	else if (attr->isUnsignedLongAttribute())
	{
		// delete integer attribute
		statement = _connection->prepare(
				"delete from attribute_integer where type=%lu and object_id=%lld",
				type,
				_objectId);
	}
	else if (attr->isByteStringAttribute() || attr -> isMechanismTypeSetAttribute())
	{
		// delete binary attribute
		statement = _connection->prepare(
				"delete from attribute_binary where type=%lu and object_id=%lld",
				type,
				_objectId);
	}
	else if (attr->isAttributeMapAttribute())
	{
		// delete attribute map attribute
		statement = _connection->prepare(
				"delete from attribute_array where type=%lu and object_id=%lld",
				type,
				_objectId);
	}

	// Statement is valid when a prepared statement has been attached to it.
	if (statement.isValid())
	{
		if (!_connection->execute(statement))
		{
			ERROR_MSG("Failed to delete attribute %lu for object %lld",type,_objectId);
			return false;
		}

		if (_transaction)
		{
			std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 _transaction->find(type);
			if (it != _transaction->end())
			{
				delete it->second;
				it->second = NULL;
			}
		}

		return true;
	}

	return false;
}

// The validity state of the object
bool DBObject::isValid()
{
	MutexLocker lock(_mutex);

	return _objectId != 0 && _connection != NULL;
}

// Start an attribute set transaction; this method is used when - for
// example - a key is generated and all its attributes need to be
// persisted in one go.
//
// N.B.: Starting a transaction locks the object!
bool DBObject::startTransaction(Access access)
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	if (_transaction)
	{
		ERROR_MSG("Transaction is already active.");
		return false;
	}

	_transaction = new std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>;
	if (_transaction == NULL)
	{
		ERROR_MSG("Not enough memory to start transaction.");
		return false;
	}

	if (_connection->inTransaction())
	{
		ERROR_MSG("Transaction in database is already active.");
		return false;
	}

	// Ask the connection to start the transaction.
	if (access == ReadWrite)
		return _connection->beginTransactionRW();
	else
		return _connection->beginTransactionRO();
}

// Commit an attribute transaction
bool DBObject::commitTransaction()
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	if (_transaction == NULL)
	{
		ERROR_MSG("No transaction active.");
		return false;
	}

	if (!_connection->commitTransaction())
	{
		return false;
	}

	// Copy the values from the internally stored transaction to the _attributes field.
	for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it = _transaction->begin(); it!=_transaction->end(); ++it) {
		std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator attr_it = _attributes.find(it->first);
		if (attr_it == _attributes.end())
		{
			_attributes[it->first] = it->second;
		}
		else
		{
			*attr_it->second = *it->second;
			delete it->second;
		}
		it->second = NULL;
	}
	delete _transaction;
	_transaction = NULL;
	return true;
}

// Abort an attribute transaction; loads back the previous version of the object from disk
bool DBObject::abortTransaction()
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}

	// Forget the atributes that were set during the transaction.
	if (_transaction)
	{
		for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it = _transaction->begin(); it!=_transaction->end(); ++it) {
			delete it->second;
			it->second = NULL;
		}
		delete _transaction;
		_transaction = NULL;
	}

	return _connection->rollbackTransaction();
}

// Destroy the object; WARNING: pointers to the object become invalid after this call
bool DBObject::destroyObject()
{
	// NOTE: Do not lock _mutex, because _token will call us back and cause a deadlock.
	// There is no need to lock anyway as _token is a non-mutable pointer, so no race
	// conditions possible.

	if (_token == NULL)
	{
		ERROR_MSG("Cannot destroy an object that is not associated with a token");
		return false;
	}

	return _token->deleteObject(this);
}