Debian Codegraph @

src/lib/object_store/ObjectFile.cpp

raw
1 /*
2 * Copyright (c) 2010 SURFnet bv
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
20 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
22 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
24 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 /*****************************************************************************
28 ObjectFile.h
29
30 This class represents object files
31 *****************************************************************************/
32
33 #include "config.h"
34 #include "ObjectFile.h"
35 #include "OSToken.h"
36 #include "OSPathSep.h"
37 #ifndef _WIN32
38 #include <unistd.h>
39 #endif
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <set>
43
44 // Attribute types
45 #define BOOLEAN_ATTR 0x1
46 #define ULONG_ATTR 0x2
47 #define BYTESTR_ATTR 0x3
48 #define ATTRMAP_ATTR 0x4
49 #define MECHSET_ATTR 0x5
50
51 // Constructor
52 ObjectFile::ObjectFile(OSToken* parent, std::string inPath, std::string inLockpath, bool isNew /* = false */)
53 {
54 path = inPath;
55 gen = Generation::create(path);
56 objectMutex = MutexFactory::i()->getMutex();
57 valid = (gen != NULL) && (objectMutex != NULL);
58 token = parent;
59 inTransaction = false;
60 transactionLockFile = NULL;
61 lockpath = inLockpath;
62
63 if (!valid) return;
64
65 if (!isNew)
66 {
67 DEBUG_MSG("Opened existing object %s", path.c_str());
68
69 refresh(true);
70 }
71 else
72 {
73 DEBUG_MSG("Created new object %s", path.c_str());
74
75 // Create an empty object file
76 store();
77 }
78
79 }
80
81 // Destructor
82 ObjectFile::~ObjectFile()
83 {
84 discardAttributes();
85
86 if (gen != NULL)
87 {
88 delete gen;
89 }
90
91 MutexFactory::i()->recycleMutex(objectMutex);
92 }
93
94 // Check if the specified attribute exists
95 bool ObjectFile::attributeExists(CK_ATTRIBUTE_TYPE type)
96 {
97 MutexLocker lock(objectMutex);
98
99 return valid && (attributes[type] != NULL);
100 }
101
102 // Retrieve the specified attribute
103 OSAttribute ObjectFile::getAttribute(CK_ATTRIBUTE_TYPE type)
104 {
105 MutexLocker lock(objectMutex);
106
107 OSAttribute* attr = attributes[type];
108 if (attr == NULL)
109 {
110 ERROR_MSG("The attribute does not exist: 0x%08X", type);
111 return OSAttribute((unsigned long)0);
112 }
113
114 return *attr;
115 }
116
117 bool ObjectFile::getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val)
118 {
119 MutexLocker lock(objectMutex);
120
121 OSAttribute* attr = attributes[type];
122 if (attr == NULL)
123 {
124 ERROR_MSG("The attribute does not exist: 0x%08X", type);
125 return val;
126 }
127
128 if (attr->isBooleanAttribute())
129 {
130 return attr->getBooleanValue();
131 }
132 else
133 {
134 ERROR_MSG("The attribute is not a boolean: 0x%08X", type);
135 return val;
136 }
137 }
138
139 unsigned long ObjectFile::getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val)
140 {
141 MutexLocker lock(objectMutex);
142
143 OSAttribute* attr = attributes[type];
144 if (attr == NULL)
145 {
146 ERROR_MSG("The attribute does not exist: 0x%08X", type);
147 return val;
148 }
149
150 if (attr->isUnsignedLongAttribute())
151 {
152 return attr->getUnsignedLongValue();
153 }
154 else
155 {
156 ERROR_MSG("The attribute is not an unsigned long: 0x%08X", type);
157 return val;
158 }
159 }
160
161 ByteString ObjectFile::getByteStringValue(CK_ATTRIBUTE_TYPE type)
162 {
163 MutexLocker lock(objectMutex);
164
165 ByteString val;
166
167 OSAttribute* attr = attributes[type];
168 if (attr == NULL)
169 {
170 ERROR_MSG("The attribute does not exist: 0x%08X", type);
171 return val;
172 }
173
174 if (attr->isByteStringAttribute())
175 {
176 return attr->getByteStringValue();
177 }
178 else
179 {
180 ERROR_MSG("The attribute is not a byte string: 0x%08X", type);
181 return val;
182 }
183 }
184
185 // Retrieve the next attribute type
186 CK_ATTRIBUTE_TYPE ObjectFile::nextAttributeType(CK_ATTRIBUTE_TYPE type)
187 {
188 MutexLocker lock(objectMutex);
189
190 std::map<CK_ATTRIBUTE_TYPE, OSAttribute*>::iterator n = attributes.upper_bound(type);
191
192 // skip null attributes
193 while ((n != attributes.end()) && (n->second == NULL))
194 ++n;
195
196 // return type or CKA_CLASS (= 0)
197 if (n == attributes.end())
198 {
199 return CKA_CLASS;
200 }
201 else
202 {
203 return n->first;
204 }
205 }
206
207 // Set the specified attribute
208 bool ObjectFile::setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute)
209 {
210 if (!valid)
211 {
212 DEBUG_MSG("Cannot update invalid object %s", path.c_str());
213
214 return false;
215 }
216
217 {
218 MutexLocker lock(objectMutex);
219
220 if (attributes[type] != NULL)
221 {
222 delete attributes[type];
223
224 attributes[type] = NULL;
225 }
226
227 attributes[type] = new OSAttribute(attribute);
228 }
229
230 store();
231
232 return valid;
233 }
234
235 // Delete the specified attribute
236 bool ObjectFile::deleteAttribute(CK_ATTRIBUTE_TYPE type)
237 {
238 if (!valid)
239 {
240 DEBUG_MSG("Cannot update invalid object %s", path.c_str());
241
242 return false;
243 }
244
245 {
246 MutexLocker lock(objectMutex);
247
248 if (attributes[type] == NULL)
249 {
250 DEBUG_MSG("Cannot delete attribute that doesn't exist in object %s", path.c_str());
251
252 return false;
253 }
254
255 delete attributes[type];
256 attributes.erase(type);
257 }
258
259 store();
260
261 return valid;
262 }
263
264 // The validity state of the object (refresh from disk as a side effect)
265 bool ObjectFile::isValid()
266 {
267 refresh();
268
269 return valid;
270 }
271
272 // Invalidate the object file externally; this method is normally
273 // only called by the OSToken class in case an object file has
274 // been deleted.
275 void ObjectFile::invalidate()
276 {
277 valid = false;
278
279 discardAttributes();
280 }
281
282 // Refresh the object if necessary
283 void ObjectFile::refresh(bool isFirstTime /* = false */)
284 {
285 // Check if we're in the middle of a transaction
286 if (inTransaction)
287 {
288 DEBUG_MSG("The object is in a transaction");
289
290 return;
291 }
292
293 // Refresh the associated token if set
294 if (!isFirstTime && (token != NULL))
295 {
296 // This may cause this instance to become invalid
297 token->index();
298 }
299
300 // Check the generation
301 if (!isFirstTime && (gen == NULL || !gen->wasUpdated()))
302 {
303 DEBUG_MSG("The object generation has not been updated");
304
305 return;
306 }
307
308 File objectFile(path);
309
310 if (!objectFile.isValid())
311 {
312 DEBUG_MSG("Object %s is invalid", path.c_str());
313
314 valid = false;
315
316 return;
317 }
318
319 objectFile.lock();
320
321 if (objectFile.isEmpty())
322 {
323 DEBUG_MSG("Object %s is empty", path.c_str());
324
325 valid = false;
326
327 return;
328 }
329
330 DEBUG_MSG("Object %s has changed", path.c_str());
331
332 // Discard the existing set of attributes
333 discardAttributes();
334
335 MutexLocker lock(objectMutex);
336
337 // Read back the generation number
338 unsigned long curGen;
339
340 if (!objectFile.readULong(curGen))
341 {
342 if (!objectFile.isEOF())
343 {
344 DEBUG_MSG("Corrupt object file %s", path.c_str());
345
346 valid = false;
347
348 objectFile.unlock();
349
350 return;
351 }
352 }
353 else
354 {
355 gen->set(curGen);
356 }
357
358 // Read back the attributes
359 while (!objectFile.isEOF())
360 {
361 unsigned long p11AttrType;
362 unsigned long osAttrType;
363
364 if (!objectFile.readULong(p11AttrType))
365 {
366 if (objectFile.isEOF())
367 {
368 break;
369 }
370
371 DEBUG_MSG("Corrupt object file %s", path.c_str());
372
373 valid = false;
374
375 objectFile.unlock();
376
377 return;
378 }
379
380 if (!objectFile.readULong(osAttrType))
381 {
382 DEBUG_MSG("Corrupt object file %s", path.c_str());
383
384 valid = false;
385
386 objectFile.unlock();
387
388 return;
389 }
390
391 // Depending on the type, read back the actual value
392 if (osAttrType == BOOLEAN_ATTR)
393 {
394 bool value;
395
396 if (!objectFile.readBool(value))
397 {
398 DEBUG_MSG("Corrupt object file %s", path.c_str());
399
400 valid = false;
401
402 objectFile.unlock();
403
404 return;
405 }
406
407 if (attributes[p11AttrType] != NULL)
408 {
409 delete attributes[p11AttrType];
410 }
411
412 attributes[p11AttrType] = new OSAttribute(value);
413 }
414 else if (osAttrType == ULONG_ATTR)
415 {
416 unsigned long value;
417
418 if (!objectFile.readULong(value))
419 {
420 DEBUG_MSG("Corrupt object file %s", path.c_str());
421
422 valid = false;
423
424 objectFile.unlock();
425
426 return;
427 }
428
429 if (attributes[p11AttrType] != NULL)
430 {
431 delete attributes[p11AttrType];
432 }
433
434 attributes[p11AttrType] = new OSAttribute(value);
435 }
436 else if (osAttrType == BYTESTR_ATTR)
437 {
438 ByteString value;
439
440 if (!objectFile.readByteString(value))
441 {
442 DEBUG_MSG("Corrupt object file %s", path.c_str());
443
444 valid = false;
445
446 objectFile.unlock();
447
448 return;
449 }
450
451 if (attributes[p11AttrType] != NULL)
452 {
453 delete attributes[p11AttrType];
454 }
455
456 attributes[p11AttrType] = new OSAttribute(value);
457 }
458 else if (osAttrType == MECHSET_ATTR)
459 {
460 std::set<CK_MECHANISM_TYPE> value;
461
462 if (!objectFile.readMechanismTypeSet(value))
463 {
464 DEBUG_MSG("Corrupt object file %s", path.c_str());
465
466 valid = false;
467
468 objectFile.unlock();
469
470 return;
471 }
472
473 if (attributes[p11AttrType] != NULL)
474 {
475 delete attributes[p11AttrType];
476 }
477
478 attributes[p11AttrType] = new OSAttribute(value);
479 }
480 else if (osAttrType == ATTRMAP_ATTR)
481 {
482 std::map<CK_ATTRIBUTE_TYPE,OSAttribute> value;
483
484 if (!objectFile.readAttributeMap(value))
485 {
486 DEBUG_MSG("Corrupt object file %s", path.c_str());
487
488 valid = false;
489
490 objectFile.unlock();
491
492 return;
493 }
494
495 if (attributes[p11AttrType] != NULL)
496 {
497 delete attributes[p11AttrType];
498 }
499
500 attributes[p11AttrType] = new OSAttribute(value);
501 }
502 else
503 {
504 DEBUG_MSG("Corrupt object file %s with unknown attribute of type %d", path.c_str(), osAttrType);
505
506 valid = false;
507
508 objectFile.unlock();
509
510 return;
511 }
512 }
513
514 objectFile.unlock();
515
516 valid = true;
517 }
518
519 // Common write part in store()
520 // called with objectFile locked and returns with objectFile unlocked
521 bool ObjectFile::writeAttributes(File &objectFile)
522 {
523 if (!gen->sync(objectFile))
524 {
525 DEBUG_MSG("Failed to synchronize generation number from object %s", path.c_str());
526
527 objectFile.unlock();
528
529 return false;
530 }
531
532 if (!objectFile.truncate())
533 {
534 DEBUG_MSG("Failed to reset object %s", path.c_str());
535
536 objectFile.unlock();
537
538 return false;
539 }
540
541 gen->update();
542
543 unsigned long newGen = gen->get();
544
545 if (!objectFile.writeULong(newGen))
546 {
547 DEBUG_MSG("Failed to write new generation number to object %s", path.c_str());
548
549 gen->rollback();
550
551 objectFile.unlock();
552
553 return false;
554 }
555
556
557 for (std::map<CK_ATTRIBUTE_TYPE, OSAttribute*>::iterator i = attributes.begin(); i != attributes.end(); i++)
558 {
559 if (i->second == NULL)
560 {
561 continue;
562 }
563
564 unsigned long p11AttrType = i->first;
565
566 if (!objectFile.writeULong(p11AttrType))
567 {
568 DEBUG_MSG("Failed to write PKCS #11 attribute type to object %s", path.c_str());
569
570 objectFile.unlock();
571
572 return false;
573 }
574
575 if (i->second->isBooleanAttribute())
576 {
577 unsigned long osAttrType = BOOLEAN_ATTR;
578 bool value = i->second->getBooleanValue();
579
580 if (!objectFile.writeULong(osAttrType) || !objectFile.writeBool(value))
581 {
582 DEBUG_MSG("Failed to write attribute to object %s", path.c_str());
583
584 objectFile.unlock();
585
586 return false;
587 }
588 }
589 else if (i->second->isUnsignedLongAttribute())
590 {
591 unsigned long osAttrType = ULONG_ATTR;
592 unsigned long value = i->second->getUnsignedLongValue();
593
594 if (!objectFile.writeULong(osAttrType) || !objectFile.writeULong(value))
595 {
596 DEBUG_MSG("Failed to write attribute to object %s", path.c_str());
597
598 objectFile.unlock();
599
600 return false;
601 }
602 }
603 else if (i->second->isByteStringAttribute())
604 {
605 unsigned long osAttrType = BYTESTR_ATTR;
606 const ByteString& value = i->second->getByteStringValue();
607
608 if (!objectFile.writeULong(osAttrType) || !objectFile.writeByteString(value))
609 {
610 DEBUG_MSG("Failed to write attribute to object %s", path.c_str());
611
612 objectFile.unlock();
613
614 return false;
615 }
616 }
617 else if (i->second->isMechanismTypeSetAttribute())
618 {
619 unsigned long osAttrType = MECHSET_ATTR;
620 const std::set<CK_MECHANISM_TYPE>& value = i->second->getMechanismTypeSetValue();
621
622 if (!objectFile.writeULong(osAttrType) || !objectFile.writeMechanismTypeSet(value))
623 {
624 DEBUG_MSG("Failed to write attribute to object %s", path.c_str());
625
626 objectFile.unlock();
627
628 return false;
629 }
630 }
631 else if (i->second->isAttributeMapAttribute())
632 {
633 unsigned long osAttrType = ATTRMAP_ATTR;
634 const std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& value = i->second->getAttributeMapValue();
635
636 if (!objectFile.writeULong(osAttrType) || !objectFile.writeAttributeMap(value))
637 {
638 DEBUG_MSG("Failed to write attribute to object %s", path.c_str());
639
640 objectFile.unlock();
641
642 return false;
643 }
644 }
645 else
646 {
647 DEBUG_MSG("Unknown attribute type for object %s", path.c_str());
648
649 objectFile.unlock();
650
651 return false;
652 }
653 }
654
655 objectFile.unlock();
656
657 return true;
658 }
659
660 // Write the object to background storage
661 void ObjectFile::store(bool isCommit /* = false */)
662 {
663 // Check if we're in the middle of a transaction
664 if (!isCommit && inTransaction)
665 {
666 return;
667 }
668
669 if (!valid)
670 {
671 DEBUG_MSG("Cannot write back an invalid object %s", path.c_str());
672
673 return;
674 }
675
676 File objectFile(path, true, true, true, false);
677
678 if (!objectFile.isValid())
679 {
680 DEBUG_MSG("Cannot open object %s for writing", path.c_str());
681
682 valid = false;
683
684 return;
685 }
686
687 objectFile.lock();
688
689 if (!isCommit) {
690 MutexLocker lock(objectMutex);
691 File lockFile(lockpath, false, true, true);
692
693 if (!writeAttributes(objectFile))
694 {
695 valid = false;
696
697 return;
698 }
699 }
700 else
701 {
702 if (!writeAttributes(objectFile))
703 {
704 valid = false;
705
706 return;
707 }
708 }
709
710 valid = true;
711 }
712
713 // Discard the cached attributes
714 void ObjectFile::discardAttributes()
715 {
716 MutexLocker lock(objectMutex);
717
718 std::map<CK_ATTRIBUTE_TYPE, OSAttribute*> cleanUp = attributes;
719 attributes.clear();
720
721 for (std::map<CK_ATTRIBUTE_TYPE, OSAttribute*>::iterator i = cleanUp.begin(); i != cleanUp.end(); i++)
722 {
723 if (i->second == NULL)
724 {
725 continue;
726 }
727
728 delete i->second;
729 i->second = NULL;
730 }
731 }
732
733
734 // Returns the file name of the object
735 std::string ObjectFile::getFilename() const
736 {
737 if ((path.find_last_of(OS_PATHSEP) != std::string::npos) &&
738 (path.find_last_of(OS_PATHSEP) < path.size()))
739 {
740 return path.substr(path.find_last_of(OS_PATHSEP) + 1);
741 }
742 else
743 {
744 return path;
745 }
746 }
747
748 // Returns the file name of the lock
749 std::string ObjectFile::getLockname() const
750 {
751 if ((lockpath.find_last_of(OS_PATHSEP) != std::string::npos) &&
752 (lockpath.find_last_of(OS_PATHSEP) < lockpath.size()))
753 {
754 return lockpath.substr(lockpath.find_last_of(OS_PATHSEP) + 1);
755 }
756 else
757 {
758 return lockpath;
759 }
760 }
761
762 // Start an attribute set transaction; this method is used when - for
763 // example - a key is generated and all its attributes need to be
764 // persisted in one go.
765 //
766 // N.B.: Starting a transaction locks the object!
767 bool ObjectFile::startTransaction(Access)
768 {
769 MutexLocker lock(objectMutex);
770
771 if (inTransaction)
772 {
773 return false;
774 }
775
776 transactionLockFile = new File(lockpath, false, true, true);
777
778 if (!transactionLockFile->isValid() || !transactionLockFile->lock())
779 {
780 delete transactionLockFile;
781 transactionLockFile = NULL;
782
783 ERROR_MSG("Failed to lock file %s for attribute transaction", lockpath.c_str());
784
785 return false;
786 }
787
788 inTransaction = true;
789
790 return true;
791 }
792
793 // Commit an attribute transaction
794 bool ObjectFile::commitTransaction()
795 {
796 MutexLocker lock(objectMutex);
797
798 if (!inTransaction)
799 {
800 return false;
801 }
802
803 if (transactionLockFile == NULL)
804 {
805 ERROR_MSG("Transaction lock file instance invalid!");
806
807 return false;
808 }
809
810 // Special store case
811 store(true);
812
813 if (!valid)
814 {
815 return false;
816 }
817
818 transactionLockFile->unlock();
819
820 delete transactionLockFile;
821 transactionLockFile = NULL;
822 inTransaction = false;
823
824 return true;
825 }
826
827 // Abort an attribute transaction; loads back the previous version of the object from disk
828 bool ObjectFile::abortTransaction()
829 {
830 {
831 MutexLocker lock(objectMutex);
832
833 if (!inTransaction)
834 {
835 return false;
836 }
837
838 if (transactionLockFile == NULL)
839 {
840 ERROR_MSG("Transaction lock file instance invalid!");
841
842 return false;
843 }
844
845 transactionLockFile->unlock();
846
847 delete transactionLockFile;
848 transactionLockFile = NULL;
849 inTransaction = false;
850 }
851
852 // Force reload from disk
853 refresh(true);
854
855 return true;
856 }
857
858 // Destroy the object; WARNING: pointers to the object become invalid after this call
859 bool ObjectFile::destroyObject()
860 {
861 if (token == NULL)
862 {
863 ERROR_MSG("Cannot destroy an object that is not associated with a token");
864
865 return false;
866 }
867
868 return token->deleteObject(this);
869 }
870