Debian Codegraph @

src/lib/object_store/File.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 vector of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this vector 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 File.h
29
30 This class wraps standard C file I/O in a convenient way for the object store
31 *****************************************************************************/
32
33 #include "config.h"
34 #include "File.h"
35 #include "log.h"
36 #include <string>
37 #include <stdio.h>
38 #include <string.h>
39 #ifndef _WIN32
40 #include <sys/file.h>
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #define F_SETLK 12
45 #define F_SETLKW 13
46 #define F_RDLCK 1
47 #define F_UNLCK 2
48 #define F_WRLCK 3
49 #endif
50 #include <sys/stat.h>
51 #include <fcntl.h>
52 #include <errno.h>
53
54 enum AttributeKind {
55 akUnknown,
56 akBoolean,
57 akInteger,
58 akBinary,
59 akAttrMap,
60 akMechSet
61 };
62
63 // Constructor
64 //
65 // N.B.: the create flag only has a function when a file is opened read/write
66 // N.B.: the truncate flag only has a function when the create one is true
67 File::File(std::string inPath, bool forRead /* = true */, bool forWrite /* = false */, bool create /* = false */, bool truncate /* = true */)
68 {
69 stream = NULL;
70
71 isReadable = forRead;
72 isWritable = forWrite;
73 locked = false;
74
75 path = inPath;
76 valid = false;
77
78 if (forRead || forWrite)
79 {
80 std::string fileMode = "";
81 int flags, fd;
82
83 #ifndef _WIN32
84 flags = 0;
85 if (forRead && !forWrite) flags |= O_RDONLY;
86 if (!forRead && forWrite) flags |= O_WRONLY | O_CREAT | O_TRUNC;
87 if (forRead && forWrite) flags |= O_RDWR;
88 if (forRead && forWrite && create) flags |= O_CREAT;
89 if (forRead && forWrite && create && truncate) flags |= O_TRUNC;
90 // Open the file
91 fd = open(path.c_str(), flags, 0600);
92 if (fd == -1)
93 {
94 ERROR_MSG("Could not open the file (%s): %s", strerror(errno), path.c_str());
95 valid = false;
96 return;
97 }
98
99 if (forRead && !forWrite) fileMode = "r";
100 if (!forRead && forWrite) fileMode = "w";
101 if (forRead && forWrite && !create) fileMode = "r+";
102 if (forRead && forWrite && create) fileMode = "w+";
103 // Open the stream
104 valid = ((stream = fdopen(fd, fileMode.c_str())) != NULL);
105 #else
106 flags = _O_BINARY;
107 if (forRead && !forWrite) flags |= _O_RDONLY;
108 if (!forRead && forWrite) flags |= _O_WRONLY | _O_CREAT | _O_TRUNC;
109 if (forRead && forWrite) flags |= _O_RDWR;
110 if (forRead && forWrite && create) flags |= _O_CREAT;
111 if (forRead && forWrite && create && truncate) flags |= _O_TRUNC;
112 // Open the file
113 fd = _open(path.c_str(), flags, _S_IREAD | _S_IWRITE);
114 if (fd == -1)
115 {
116 ERROR_MSG("Could not open the file (%s): %s", strerror(errno), path.c_str());
117 valid = false;
118 return;
119 }
120
121 if (forRead && !forWrite) fileMode = "rb";
122 if (!forRead && forWrite) fileMode = "wb";
123 if (forRead && forWrite && !create) fileMode = "rb+";
124 if (forRead && forWrite && create) fileMode = "wb+";
125 // Open the stream
126 valid = ((stream = _fdopen(fd, fileMode.c_str())) != NULL);
127 #endif
128 }
129 }
130
131 // Destructor
132 File::~File()
133 {
134 if (locked)
135 {
136 unlock();
137 }
138
139 if (stream != NULL)
140 {
141 fclose(stream);
142 }
143 }
144
145 // Check if the file is valid
146 bool File::isValid()
147 {
148 return valid;
149 }
150
151 // Check if the file is readable
152 bool File::isRead()
153 {
154 return isReadable;
155 }
156
157 // Check if the file is writable
158 bool File::isWrite()
159 {
160 return isWritable;
161 }
162
163 // Check if the file is empty
164 bool File::isEmpty()
165 {
166 #ifndef _WIN32
167 struct stat s;
168
169 if (fstat(fileno(stream), &s) != 0)
170 {
171 valid = false;
172
173 return false;
174 }
175
176 return (s.st_size == 0);
177 #else
178 struct _stat s;
179
180 if (_fstat(_fileno(stream), &s) != 0)
181 {
182 valid = false;
183
184 return false;
185 }
186
187 return (s.st_size == 0);
188 #endif
189 }
190
191 // Check if the end-of-file was reached
192 bool File::isEOF()
193 {
194 return valid && feof(stream);
195 }
196
197 // Read an unsigned long value; warning: not thread safe without locking!
198 bool File::readULong(unsigned long& value)
199 {
200 if (!valid) return false;
201
202 ByteString ulongVal;
203
204 ulongVal.resize(8);
205
206 if (fread(&ulongVal[0], 1, 8, stream) != 8)
207 {
208 return false;
209 }
210
211 value = ulongVal.long_val();
212
213 return true;
214 }
215
216 // Read a ByteString value; warning: not thread safe without locking!
217 bool File::readByteString(ByteString& value)
218 {
219 if (!valid) return false;
220
221 // Retrieve the length to read from the file
222 unsigned long len;
223
224 if (!readULong(len))
225 {
226 return false;
227 }
228
229 // Read the byte string from the file
230 value.resize(len);
231
232 if (len == 0)
233 {
234 return true;
235 }
236
237 if (fread(&value[0], 1, len, stream) != len)
238 {
239 return false;
240 }
241
242 return true;
243 }
244
245 // Read a boolean value; warning: not thread safe without locking!
246 bool File::readBool(bool& value)
247 {
248 if (!valid) return false;
249
250 // Read the boolean from the file
251 unsigned char boolValue;
252
253 if (fread(&boolValue, 1, 1, stream) != 1)
254 {
255 return false;
256 }
257
258 value = boolValue ? true : false;
259
260 return true;
261 }
262
263 // Read a mechanism type set value; warning: not thread safe without locking!
264 bool File::readMechanismTypeSet(std::set<CK_MECHANISM_TYPE>& value)
265 {
266 if (!valid) return false;
267
268 unsigned long count;
269 if (!readULong(count)) return false;
270
271 for (unsigned long i = 0; i < count; i++)
272 {
273 unsigned long mechType;
274 if (!readULong(mechType))
275 {
276 return false;
277 }
278
279 value.insert((CK_MECHANISM_TYPE) mechType);
280 }
281
282 return true;
283 }
284
285 // Read an attribute map value; warning: not thread safe without locking!
286 bool File::readAttributeMap(std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& value)
287 {
288 if (!valid) return false;
289
290 // Retrieve the length to read from the file
291 unsigned long len;
292
293 if (!readULong(len))
294 {
295 return false;
296 }
297
298 while (len != 0)
299 {
300 unsigned long attrType;
301 if (!readULong(attrType))
302 {
303 return false;
304 }
305 if (8 > len)
306 {
307 return false;
308 }
309 len -= 8;
310
311 unsigned long attrKind;
312 if (!readULong(attrKind))
313 {
314 return false;
315 }
316 if (8 > len)
317 {
318 return false;
319 }
320 len -= 8;
321
322 switch (attrKind)
323 {
324 case akBoolean:
325 {
326 bool val;
327 if (!readBool(val))
328 {
329 return false;
330 }
331 if (1 > len)
332 {
333 return false;
334 }
335 len -= 1;
336
337 value.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, val));
338 }
339 break;
340
341 case akInteger:
342 {
343 unsigned long val;
344 if (!readULong(val))
345 {
346 return false;
347 }
348 if (8 > len)
349 {
350 return false;
351 }
352 len -= 8;
353
354 value.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, val));
355 }
356 break;
357
358 case akBinary:
359 {
360 ByteString val;
361 if (!readByteString(val))
362 {
363 return false;
364 }
365 if (8 + val.size() > len)
366 {
367 return false;
368 }
369 len -= 8 + val.size();
370
371 value.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, val));
372 }
373 break;
374
375 case akMechSet:
376 {
377 std::set<CK_MECHANISM_TYPE> val;
378 if (!readMechanismTypeSet(val))
379 {
380 return false;
381 }
382 if (8 + val.size() * 8 > len)
383 {
384 return false;
385 }
386 len -= 8 + val.size() * 8;
387
388 value.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, val));
389 }
390 break;
391
392 default:
393 return false;
394 }
395 }
396
397 return true;
398 }
399
400 // Read a string value; warning: not thread safe without locking!
401 bool File::readString(std::string& value)
402 {
403 if (!valid) return false;
404
405 // Retrieve the length to read from the file
406 unsigned long len;
407
408 if (!readULong(len))
409 {
410 return false;
411 }
412
413 // Read the string from the file
414 value.resize(len);
415
416 if (fread(&value[0], 1, len, stream) != len)
417 {
418 return false;
419 }
420
421 return true;
422 }
423
424 // Write an unsigned long value; warning: not thread safe without locking!
425 bool File::writeULong(const unsigned long value)
426 {
427 if (!valid) return false;
428
429 ByteString toWrite(value);
430
431 // Write the value to the file
432 if (fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size())
433 {
434 return false;
435 }
436
437 return true;
438 }
439
440 // Write a ByteString value; warning: not thread safe without locking!
441 bool File::writeByteString(const ByteString& value)
442 {
443 if (!valid) return false;
444
445 ByteString toWrite = value.serialise();
446
447 // Write the value to the file
448 if (fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size())
449 {
450 return false;
451 }
452
453 return true;
454 }
455
456 // Write a string value; warning: not thread safe without locking!
457 bool File::writeString(const std::string& value)
458 {
459 if (!valid) return false;
460
461 ByteString toWrite((unsigned long) value.size());
462
463 // Write the value to the file
464 if ((fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size()) ||
465 (fwrite(&value[0], 1, value.size(), stream) != value.size()))
466 {
467 return false;
468 }
469
470 return true;
471 }
472
473 // Write a mechanism type set value; warning: not thread safe without locking!
474 bool File::writeMechanismTypeSet(const std::set<CK_MECHANISM_TYPE>& value)
475 {
476 if (!valid) return false;
477
478 // write length
479 if (!writeULong(value.size()))
480 {
481 return false;
482 }
483
484 // write each value
485 for (std::set<CK_MECHANISM_TYPE>::const_iterator i = value.begin(); i != value.end(); ++i)
486 {
487 if (!writeULong(*i)) return false;
488 }
489
490 return true;
491 }
492
493 // Write an attribute map value; warning: not thread safe without locking!
494 bool File::writeAttributeMap(const std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& value)
495 {
496 if (!valid) return false;
497
498 // compute length
499 unsigned long len = 0;
500 for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute>::const_iterator i = value.begin(); i != value.end(); ++i)
501 {
502 OSAttribute attr = i->second;
503 // count attribute type and kind
504 len += 8 + 8;
505
506 if (attr.isBooleanAttribute())
507 {
508 len += 1;
509 }
510 else if (attr.isUnsignedLongAttribute())
511 {
512 len += 8;
513 }
514 else if (attr.isByteStringAttribute())
515 {
516 ByteString val = attr.getByteStringValue();
517 len += 8 + val.size();
518 }
519 else if (attr.isMechanismTypeSetAttribute())
520 {
521 std::set<CK_MECHANISM_TYPE> val = attr.getMechanismTypeSetValue();
522 len += 8 + val.size() * 8;
523 }
524 else
525 {
526 return false;
527 }
528 }
529
530 // write length
531 if (!writeULong(len))
532 {
533 return false;
534 }
535
536 // write each attribute
537 for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute>::const_iterator i = value.begin(); i != value.end(); ++i)
538 {
539 OSAttribute attr = i->second;
540 unsigned long attrType = (unsigned long) i->first;
541 if (!writeULong(attrType))
542 {
543 return false;
544 }
545
546 if (attr.isBooleanAttribute())
547 {
548 unsigned long attrKind = akBoolean;
549 if (!writeULong(attrKind))
550 {
551 return false;
552 }
553
554 bool val = attr.getBooleanValue();
555 if (!writeBool(val))
556 {
557 return false;
558 }
559 }
560 else if (attr.isUnsignedLongAttribute())
561 {
562 unsigned long attrKind = akInteger;
563 if (!writeULong(attrKind))
564 {
565 return false;
566 }
567
568 unsigned long val = attr.getUnsignedLongValue();
569 if (!writeULong(val))
570 {
571 return false;
572 }
573 }
574 else if (attr.isByteStringAttribute())
575 {
576 unsigned long attrKind = akBinary;
577 if (!writeULong(attrKind))
578 {
579 return false;
580 }
581
582 ByteString val = attr.getByteStringValue();
583 if (!writeByteString(val))
584 {
585 return false;
586 }
587 }
588 else if (attr.isMechanismTypeSetAttribute())
589 {
590 unsigned long attrKind = akMechSet;
591 if (!writeULong(attrKind))
592 {
593 return false;
594 }
595
596 std::set<CK_MECHANISM_TYPE> val = attr.getMechanismTypeSetValue();
597 if (!writeMechanismTypeSet(val))
598 {
599 return false;
600 }
601 }
602 }
603
604 return true;
605 }
606
607 // Write a boolean value; warning: not thread safe without locking!
608 bool File::writeBool(const bool value)
609 {
610 if (!valid) return false;
611
612 unsigned char toWrite = value ? 0xFF : 0x00;
613
614 // Write the value to the file
615 if (fwrite(&toWrite, 1, 1, stream) != 1)
616 {
617 return false;
618 }
619
620 return true;
621 }
622
623 // Rewind the file
624 bool File::rewind()
625 {
626 if (!valid) return false;
627
628 ::rewind(stream);
629
630 return true;
631 }
632
633 // Truncate the file
634 bool File::truncate()
635 {
636 if (!valid) return false;
637
638 #ifndef _WIN32
639 return (::ftruncate(fileno(stream), 0) == 0);
640 #else
641 return (_chsize(_fileno(stream), 0) == 0);
642 #endif
643 }
644
645 // Seek to the specified position relative to the start of the file; if no
646 // argument is specified this operation seeks to the end of the file
647 bool File::seek(long offset /* = -1 */)
648 {
649 if (offset == -1)
650 {
651 return valid && (valid = !fseek(stream, 0, SEEK_END));
652 }
653 else
654 {
655 return valid && (valid = !fseek(stream, offset, SEEK_SET));
656 }
657 }
658
659 // Lock the file
660 bool File::lock(bool block /* = true */)
661 {
662 #ifndef _WIN32
663 struct flock fl;
664 fl.l_type = isWrite() ? F_WRLCK : F_RDLCK;
665 fl.l_whence = SEEK_SET;
666 fl.l_start = 0;
667 fl.l_len = 0;
668 fl.l_pid = 0;
669
670 if (locked || !valid) return false;
671
672 if (fcntl(fileno(stream), block ? F_SETLKW : F_SETLK, &fl) != 0)
673 {
674 ERROR_MSG("Could not lock the file: %s", strerror(errno));
675 return false;
676 }
677 #else
678 HANDLE hFile;
679 DWORD flags = 0;
680 OVERLAPPED o;
681
682 if (isWrite()) flags |= LOCKFILE_EXCLUSIVE_LOCK;
683 if (!block) flags |= LOCKFILE_FAIL_IMMEDIATELY;
684
685 if (locked || !valid) return false;
686
687 hFile = (HANDLE) _get_osfhandle(_fileno(stream));
688 if (hFile == INVALID_HANDLE_VALUE)
689 {
690 ERROR_MSG("Invalid handle");
691 return false;
692 }
693
694 memset(&o, 0, sizeof(o));
695 if (!LockFileEx(hFile, flags, 0, 1, 0, &o))
696 {
697 DWORD rv = GetLastError();
698
699 ERROR_MSG("Could not lock the file: 0x%08x", rv);
700 return false;
701 }
702 #endif
703
704 locked = true;
705
706 return true;
707 }
708
709 // Unlock the file
710 bool File::unlock()
711 {
712 #ifndef _WIN32
713 struct flock fl;
714 fl.l_type = F_UNLCK;
715 fl.l_whence = SEEK_SET;
716 fl.l_start = 0;
717 fl.l_len = 0;
718 fl.l_pid = 0;
719
720 if (!locked || !valid) return false;
721
722 if (fcntl(fileno(stream), F_SETLK, &fl) != 0)
723 {
724 valid = false;
725
726 ERROR_MSG("Could not unlock the file: %s", strerror(errno));
727 return false;
728 }
729 #else
730 HANDLE hFile;
731 OVERLAPPED o;
732
733 if (!locked || !valid) return false;
734
735 hFile = (HANDLE) _get_osfhandle(_fileno(stream));
736 if (hFile == INVALID_HANDLE_VALUE)
737 {
738 ERROR_MSG("Invalid handle");
739 return false;
740 }
741
742 memset(&o, 0, sizeof(o));
743 if (!UnlockFileEx(hFile, 0, 1, 0, &o))
744 {
745 DWORD rv = GetLastError();
746
747 valid = false;
748
749 ERROR_MSG("Could not unlock the file: 0x%08x", rv);
750 return false;
751 }
752 #endif
753
754
755 locked = false;
756
757 return valid;
758 }
759
760 // Flush the buffered stream to background storage
761 bool File::flush()
762 {
763 return valid && !fflush(stream);
764 }
765