aboutsummaryrefslogtreecommitdiffstats
path: root/SoftHSMv2/src/lib/object_store/File.cpp
blob: 2af8ea9470668fa15552717657d1c60fc141ca7a (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
/*
 * Copyright (c) 2010 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 vector of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this vector 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.
 */

/*****************************************************************************
 File.h

 This class wraps standard C file I/O in a convenient way for the object store
 *****************************************************************************/

#include "config.h"
#include "File.h"
#include "log.h"
#include <string>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <sys/file.h>
#include <unistd.h>
#else
#include <io.h>
#define F_SETLK		12
#define F_SETLKW	13
#define F_RDLCK		1
#define F_UNLCK		2
#define F_WRLCK		3
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

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

// Constructor
//
// N.B.: the create flag only has a function when a file is opened read/write
// N.B.: the truncate flag only has a function when the create one is true
File::File(std::string inPath, bool forRead /* = true */, bool forWrite /* = false */, bool create /* = false */, bool truncate /* = true */)
{
	stream = NULL;

	isReadable = forRead;
	isWritable = forWrite;
	locked = false;

	path = inPath;
	valid = false;

	if (forRead || forWrite)
	{
		std::string fileMode = "";
		int flags, fd;

#ifndef _WIN32
		flags = 0;
		if (forRead && !forWrite) flags |= O_RDONLY;
		if (!forRead && forWrite) flags |= O_WRONLY | O_CREAT | O_TRUNC;
		if (forRead && forWrite) flags |= O_RDWR;
		if (forRead && forWrite && create) flags |= O_CREAT;
		if (forRead && forWrite && create && truncate) flags |= O_TRUNC;
		// Open the file
		fd = open(path.c_str(), flags, 0600);
		if (fd == -1)
		{
			ERROR_MSG("Could not open the file (%s): %s", strerror(errno), path.c_str());
			valid = false;
			return;
		}

		if (forRead && !forWrite) fileMode = "r";
		if (!forRead && forWrite) fileMode = "w";
		if (forRead && forWrite && !create) fileMode = "r+";
		if (forRead && forWrite && create) fileMode = "w+";
		// Open the stream
		valid = ((stream = fdopen(fd, fileMode.c_str())) != NULL);
#else
		flags = _O_BINARY;
		if (forRead && !forWrite) flags |= _O_RDONLY;
		if (!forRead && forWrite) flags |= _O_WRONLY | _O_CREAT | _O_TRUNC;
		if (forRead && forWrite) flags |= _O_RDWR;
		if (forRead && forWrite && create) flags |= _O_CREAT;
		if (forRead && forWrite && create && truncate) flags |= _O_TRUNC;
		// Open the file
		fd = _open(path.c_str(), flags, _S_IREAD | _S_IWRITE);
		if (fd == -1)
		{
			ERROR_MSG("Could not open the file (%s): %s", strerror(errno), path.c_str());
			valid = false;
			return;
		}

		if (forRead && !forWrite) fileMode = "rb";
		if (!forRead && forWrite) fileMode = "wb";
		if (forRead && forWrite && !create) fileMode = "rb+";
		if (forRead && forWrite && create) fileMode = "wb+";
		// Open the stream
		valid = ((stream = _fdopen(fd, fileMode.c_str())) != NULL);
#endif
	}
}

// Destructor
File::~File()
{
	if (locked)
	{
		unlock();
	}

	if (stream != NULL)
	{
		fclose(stream);
	}
}

// Check if the file is valid
bool File::isValid()
{
	return valid;
}

// Check if the file is readable
bool File::isRead()
{
	return isReadable;
}

// Check if the file is writable
bool File::isWrite()
{
	return isWritable;
}

// Check if the file is empty
bool File::isEmpty()
{
#ifndef _WIN32
	struct stat s;

	if (fstat(fileno(stream), &s) != 0)
	{
		valid = false;

		return false;
	}

	return (s.st_size == 0);
#else
	struct _stat s;

	if (_fstat(_fileno(stream), &s) != 0)
	{
		valid = false;

		return false;
	}

	return (s.st_size == 0);
#endif
}

// Check if the end-of-file was reached
bool File::isEOF()
{
	return valid && feof(stream);
}

// Read an unsigned long value; warning: not thread safe without locking!
bool File::readULong(unsigned long& value)
{
	if (!valid) return false;

	ByteString ulongVal;

	ulongVal.resize(8);

	if (fread(&ulongVal[0], 1, 8, stream) != 8)
	{
		return false;
	}

	value = ulongVal.long_val();

	return true;
}

// Read a ByteString value; warning: not thread safe without locking!
bool File::readByteString(ByteString& value)
{
	if (!valid) return false;

	// Retrieve the length to read from the file
	unsigned long len;

	if (!readULong(len))
	{
		return false;
	}

	// Read the byte string from the file
	value.resize(len);

	if (len == 0)
	{
		return true;
	}

	if (fread(&value[0], 1, len, stream) != len)
	{
		return false;
	}

	return true;
}

// Read a boolean value; warning: not thread safe without locking!
bool File::readBool(bool& value)
{
	if (!valid) return false;

	// Read the boolean from the file
	unsigned char boolValue;

	if (fread(&boolValue, 1, 1, stream) != 1)
	{
		return false;
	}

	value = boolValue ? true : false;

	return true;
}

// Read a mechanism type set value; warning: not thread safe without locking!
bool File::readMechanismTypeSet(std::set<CK_MECHANISM_TYPE>& value)
{
	if (!valid) return false;

	unsigned long count;
	if (!readULong(count)) return false;

	for (unsigned long i = 0; i < count; i++)
	{
		unsigned long mechType;
		if (!readULong(mechType))
		{
			return false;
		}

		value.insert((CK_MECHANISM_TYPE) mechType);
	}

	return true;
}

// Read an attribute map value; warning: not thread safe without locking!
bool File::readAttributeMap(std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& value)
{
	if (!valid) return false;

	// Retrieve the length to read from the file
	unsigned long len;

	if (!readULong(len))
	{
		return false;
	}

	while (len != 0)
	{
		unsigned long attrType;
		if (!readULong(attrType))
		{
			return false;
		}
		if (8 > len)
		{
			return false;
		}
		len -= 8;

		unsigned long attrKind;
		if (!readULong(attrKind))
		{
			return false;
		}
		if (8 > len)
		{
			return false;
		}
		len -= 8;

		switch (attrKind)
		{
			case akBoolean:
			{
				bool val;
				if (!readBool(val))
				{
					return false;
				}
				if (1 > len)
				{
					return false;
				}
				len -= 1;

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

			case akInteger:
			{
				unsigned long val;
				if (!readULong(val))
				{
					return false;
				}
				if (8 > len)
				{
					return false;
				}
				len -= 8;

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

			case akBinary:
			{
				ByteString val;
				if (!readByteString(val))
				{
					return false;
				}
				if (8 + val.size() > len)
				{
					return false;
				}
				len -= 8 + val.size();

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

			case akMechSet:
			{
				std::set<CK_MECHANISM_TYPE> val;
				if (!readMechanismTypeSet(val))
				{
					return false;
				}
				if (8 + val.size() * 8 > len)
				{
					return false;
				}
				len -= 8 + val.size() * 8;

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

			default:
				return false;
		}
	}

	return true;
}

// Read a string value; warning: not thread safe without locking!
bool File::readString(std::string& value)
{
	if (!valid) return false;

	// Retrieve the length to read from the file
	unsigned long len;

	if (!readULong(len))
	{
		return false;
	}

	// Read the string from the file
	value.resize(len);

	if (fread(&value[0], 1, len, stream) != len)
	{
		return false;
	}

	return true;
}

// Write an unsigned long value; warning: not thread safe without locking!
bool File::writeULong(const unsigned long value)
{
	if (!valid) return false;

	ByteString toWrite(value);

	// Write the value to the file
	if (fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size())
	{
		return false;
	}

	return true;
}

// Write a ByteString value; warning: not thread safe without locking!
bool File::writeByteString(const ByteString& value)
{
	if (!valid) return false;

	ByteString toWrite = value.serialise();

	// Write the value to the file
	if (fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size())
	{
		return false;
	}

	return true;
}

// Write a string value; warning: not thread safe without locking!
bool File::writeString(const std::string& value)
{
	if (!valid) return false;

	ByteString toWrite((const unsigned long) value.size());

	// Write the value to the file
	if ((fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size()) ||
	    (fwrite(&value[0], 1, value.size(), stream) != value.size()))
	{
		return false;
	}

	return true;
}

// Write a mechanism type set value; warning: not thread safe without locking!
bool File::writeMechanismTypeSet(const std::set<CK_MECHANISM_TYPE>& value)
{
	if (!valid) return false;

	// write length
	if (!writeULong(value.size()))
	{
		return false;
	}

	// write each value
	for (std::set<CK_MECHANISM_TYPE>::const_iterator i = value.begin(); i != value.end(); ++i)
	{
		if (!writeULong(*i)) return false;
	}

	return true;
}

// Write an attribute map value; warning: not thread safe without locking!
bool File::writeAttributeMap(const std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& value)
{
	if (!valid) return false;

	// compute length
	unsigned long len = 0;
	for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute>::const_iterator i = value.begin(); i != value.end(); ++i)
	{
		OSAttribute attr = i->second;
		// count attribute type and kind
		len += 8 + 8;

		if (attr.isBooleanAttribute())
		{
			len += 1;
		}
		else if (attr.isUnsignedLongAttribute())
		{
			len += 8;
		}
		else if (attr.isByteStringAttribute())
		{
			ByteString val = attr.getByteStringValue();
			len += 8 + val.size();
		}
		else if (attr.isMechanismTypeSetAttribute())
		{
			std::set<CK_MECHANISM_TYPE> val = attr.getMechanismTypeSetValue();
			len += 8 + val.size() * 8;
		}
		else
		{
			return false;
		}
	}

	// write length
	if (!writeULong(len))
	{
		return false;
	}

	// write each attribute
	for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute>::const_iterator i = value.begin(); i != value.end(); ++i)
	{
		OSAttribute attr = i->second;
		unsigned long attrType = (unsigned long) i->first;
		if (!writeULong(attrType))
		{
			return false;
		}

		if (attr.isBooleanAttribute())
		{
			unsigned long attrKind = akBoolean;
			if (!writeULong(attrKind))
			{
				return false;
			}

			bool val = attr.getBooleanValue();
			if (!writeBool(val))
			{
				return false;
			}
		}
		else if (attr.isUnsignedLongAttribute())
		{
			unsigned long attrKind = akInteger;
			if (!writeULong(attrKind))
			{
				return false;
			}

			unsigned long val = attr.getUnsignedLongValue();
			if (!writeULong(val))
			{
				return false;
			}
		}
		else if (attr.isByteStringAttribute())
		{
			unsigned long attrKind = akBinary;
			if (!writeULong(attrKind))
			{
				return false;
			}

			ByteString val = attr.getByteStringValue();
			if (!writeByteString(val))
			{
				return false;
			}
		}
		else if (attr.isMechanismTypeSetAttribute())
		{
			unsigned long attrKind = akMechSet;
			if (!writeULong(attrKind))
			{
				return false;
			}

			std::set<CK_MECHANISM_TYPE> val = attr.getMechanismTypeSetValue();
			if (!writeMechanismTypeSet(val))
			{
				return false;
			}
		}
	}

	return true;
}

// Write a boolean value; warning: not thread safe without locking!
bool File::writeBool(const bool value)
{
	if (!valid) return false;

	unsigned char toWrite = value ? 0xFF : 0x00;

	// Write the value to the file
	if (fwrite(&toWrite, 1, 1, stream) != 1)
	{
		return false;
	}

	return true;
}

// Rewind the file
bool File::rewind()
{
	if (!valid) return false;

	::rewind(stream);

	return true;
}

// Truncate the file
bool File::truncate()
{
	if (!valid) return false;

#ifndef _WIN32
	return (::ftruncate(fileno(stream), 0) == 0);
#else
	return (_chsize(_fileno(stream), 0) == 0);
#endif
}

// Seek to the specified position relative to the start of the file; if no
// argument is specified this operation seeks to the end of the file
bool File::seek(long offset /* = -1 */)
{
	if (offset == -1)
	{
		return valid && (valid = !fseek(stream, 0, SEEK_END));
	}
	else
	{
		return valid && (valid = !fseek(stream, offset, SEEK_SET));
	}
}

// Lock the file
bool File::lock(bool block /* = true */)
{
#ifndef _WIN32
	struct flock fl;
	fl.l_type = isWrite() ? F_WRLCK : F_RDLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_pid = 0;

	if (locked || !valid) return false;

	if (fcntl(fileno(stream), block ? F_SETLKW : F_SETLK, &fl) != 0)
	{
		ERROR_MSG("Could not lock the file: %s", strerror(errno));
		return false;
	}
#else
	HANDLE hFile;
	DWORD flags = 0;
	OVERLAPPED o;

	if (isWrite()) flags |= LOCKFILE_EXCLUSIVE_LOCK;
	if (!block) flags |= LOCKFILE_FAIL_IMMEDIATELY;

	if (locked || !valid) return false;

	hFile = (HANDLE) _get_osfhandle(_fileno(stream));
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ERROR_MSG("Invalid handle");
		return false;
	}

	memset(&o, 0, sizeof(o));
	if (!LockFileEx(hFile, flags, 0, 1, 0, &o))
	{
		DWORD rv = GetLastError();

		ERROR_MSG("Could not lock the file: 0x%08x", rv);
		return false;
	}
#endif

	locked = true;

	return true;
}

// Unlock the file
bool File::unlock()
{
#ifndef _WIN32
	struct flock fl;
	fl.l_type = F_UNLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_pid = 0;

	if (!locked || !valid) return false;

	if (fcntl(fileno(stream), F_SETLK, &fl) != 0)
	{
		valid = false;

		ERROR_MSG("Could not unlock the file: %s", strerror(errno));
		return false;
	}
#else
	HANDLE hFile;
	OVERLAPPED o;

	if (!locked || !valid) return false;

	hFile = (HANDLE) _get_osfhandle(_fileno(stream));
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ERROR_MSG("Invalid handle");
		return false;
	}

	memset(&o, 0, sizeof(o));
	if (!UnlockFileEx(hFile, 0, 1, 0, &o))
	{
		DWORD rv = GetLastError();

		valid = false;

		ERROR_MSG("Could not unlock the file: 0x%08x", rv);
		return  false;
	}
#endif
			

	locked = false;

	return valid;
}

// Flush the buffered stream to background storage
bool File::flush()
{
	return valid && !fflush(stream);
}