File: file.cc

package info (click to toggle)
yapet 0.6-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 6,012 kB
  • ctags: 2,913
  • sloc: ansic: 13,661; cpp: 11,384; sh: 4,814; makefile: 847; yacc: 291; sed: 16
file content (1006 lines) | stat: -rw-r--r-- 27,836 bytes parent folder | download
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
// $Id: file.cc 2849 2009-09-01 10:50:34Z rafi $
//
// Copyright (C) 2008, 2009  Rafael Ostertag
//
// This file is part of YAPET.
//
// YAPET is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// YAPET is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// YAPET.  If not, see <http://www.gnu.org/licenses/>.
//
// Additional permission under GNU GPL version 3 section 7
//
// If you modify this program, or any covered work, by linking or combining it
// with the OpenSSL project's OpenSSL library (or a modified version of that
// library), containing parts covered by the terms of the OpenSSL or SSLeay
// licenses, Rafael Ostertag grants you additional permission to convey the
// resulting work.  Corresponding Source for a non-source form of such a
// combination shall include the source code for the parts of OpenSSL used as
// well as that of the covered work.
//

#include "../intl.h"
#include "crypt.h"
#include "record.h"
#include "structs.h"
#include "file.h"

#ifdef TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# ifdef HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif // TIME_WITH_SYS_TIME

#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif

#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif

#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif

#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif

#ifdef HAVE_STRING_H
# include <string.h>
#endif

#ifdef HAVE_ERRNO_H
# include <errno.h>
#endif

#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#ifdef HAVE_ALLOCA_H
# include <alloca.h>
#elif defined __GNUC__
# define alloca __builtin_alloca
#elif defined _AIX
# define alloca __alloca
#elif defined _MSC_VER
# include <malloc.h>
# define alloca _alloca
#else
# include <stddef.h>
#endif

using namespace YAPET;

/**
 * @brief The control string for the file header.
 *
 * This is the control string used for the file header to verify the
 * decryption of the header. It is stored in the file header. When the
 * key is verified, the header is read and this string is compared to
 * the one stored in the file header. If they don't match, the class
 * assumes the key provided is invalid.
 */
const char CONTROL_STR[] = "ABCDEFGHIJKLMNOPQRSTUVW";

/**
 * @brief The recognition string.
 *
 * The recognition string is saved plain-text at the very beginning of
 * each file. When files are opened, the methods check for the
 * existence of this string. If this string is not found, the methods
 * report an unknown file.
 */
const char RECOG_STR[] = "YAPET1.0";

/**
 * Checks the permission and owner of a file for security.
 *
 * It throws a \c YAPETRetryException if the owner of the file does not match
 * the uid of the owner of the process, or if the mode is not \c
 * (S_IRUSR|S_IWUSR).
 */
void
File::checkFileSecurity() throw (YAPETException) {
#if defined(HAVE_FSTAT) && defined(HAVE_GETUID)
    struct stat buf;
    int err = fstat (fd, &buf);

    if (err == -1)
        throw YAPETException (strerror (errno) );

    uid_t uid = getuid();

    if (buf.st_uid != uid) {
        std::string tmp (_ ("You are not the owner of ") );
        throw YAPETRetryException (tmp + filename);
    }

    if (buf.st_mode != (S_IFREG | S_IRUSR | S_IWUSR) ) {
        std::string tmp1 (_ ("Permissions of ") );
        std::string tmp2 (_ (" not secure.") );
        throw YAPETRetryException (tmp1 + filename + tmp2);
    }

#endif
}

/**
 * Sets the owner and permissions on a file in a manner that \c
 * File::checkFileSecurity does not complain.
 *
 * If it cannot set the security permissions, it throws a \c
 * YAPETRetryException if the error can be avoided using non-secure settings.
 */
void
File::setFileSecurity() throw (YAPETException) {
#if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD) && defined(HAVE_FSTAT)
    struct stat buf;
    int err = fstat (fd, &buf);

    if (err == -1)
        throw YAPETException (strerror (errno) );

    err = fchown (fd, getuid(), buf.st_gid);

    if (err == -1) {
        std::string tmp (_ ("Cannot set the owner of ") );
        throw YAPETRetryException (tmp + filename);
    }

    err = fchmod (fd, S_IRUSR | S_IWUSR);

    if (err == -1) {
        std::string tmp (_ ("Cannot set file permissions on ") );
        throw YAPETRetryException (tmp + filename);
    }

#endif
}


/**
 * Creates a file with name specified in \c filename and sets \c fd to
 * the obtained file descriptor. The file is opened for read-write.
 *
 */
void
File::openCreate() throw (YAPETException) {
    fd = ::open (filename.c_str(),
                 O_RDWR | O_CREAT | O_TRUNC | O_APPEND,
                 (usefsecurity ? S_IRUSR | S_IWUSR :
                  S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) );

    if (fd == -1)
        throw YAPETException (strerror (errno) );

    if (usefsecurity)
        checkFileSecurity();
}

/**
 * Opens an existing file in read-write mode. If the file does not
 * exist, the method throws an exception.
 */
void
File::openNoCreate() throw (YAPETException) {
    fd = ::open (filename.c_str(), O_RDWR | O_APPEND);

    if (fd == -1)
        throw YAPETException (strerror (errno) );

    if (usefsecurity)
        checkFileSecurity();
}

/**
 * Returns the time of the last modification of the file specified by
 * \c fd.
 *
 * @return a \c time_t holdign the last modification date.
 */
int64_t
File::lastModified() const throw (YAPETException) {
    struct stat st_buf;
    int retval = fstat (fd, &st_buf);

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    return st_buf.st_mtime;
}

/**
 * Seeks \c offset bytes from the current position in the file
 * specified by \c fd.
 *
 * @param offset the offset in bytes from the current position in the
 * file.
 */
void
File::seekCurr (off_t offset) const throw (YAPETException) {
    off_t pos = lseek (fd, offset, SEEK_CUR);

    if ( ( (off_t) - 1) == pos)
        throw YAPETException (strerror (errno) );
}

/**
 * Seeks \c offset bytes from the beginning of the file.
 *
 * @param offset the offset in bytes from the beginning.
 */
void
File::seekAbs (off_t offset) const throw (YAPETException) {
    off_t pos = lseek (fd, offset, SEEK_SET);

    if ( ( (off_t) - 1) == pos)
        throw YAPETException (strerror (errno) );

    if (pos != offset)
        throw YAPETException (_ ("Error seeking within file: ") + filename);
}

/**
 * Truncates the file up to the header by creating a new empty file
 * copying over the existing header.
 *
 */
void
File::preparePWSave() throw (YAPETException) {
    BDBuffer* curr_header = readHeader();
    ::close (fd);

    try {
        openCreate();
    } catch (YAPETException& ex) {
        if (curr_header != NULL)
            delete curr_header;

        throw;
    }

    mtime = lastModified();
    writeHeader (*curr_header);
    delete curr_header;
}

/**
 * Seeks to the first password record in the file. The file pointer is
 * set to point to the record length indicator, so that a call to \c
 * read() will return the first password record.
 */
void
File::seekDataSection() const throw (YAPETException) {
    seekAbs (strlen (RECOG_STR) );
    uint32_t len;
    int retval = ::read (fd, &len, sizeof (uint32_t) );

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if ( ( (size_t) retval) != sizeof (uint32_t) )
        throw YAPETException (_ ("Unable to seek to data section") );

    len = int_from_disk<uint32_t> (len);
    seekCurr (len);
}

/**
 * Reads from the current position in the file. The method expects the
 * file pointer to point a record length indicator. In other words, it
 * first reads four bytes from the current file position, which will
 * give it a clue about the length of the encrypted record to read.
 *
 * It then reads as many bytes as indicated from the file and returns
 * the data read in a \c BDBuffer. The memory allocated by the \c
 * BDBuffer has to be freed by the caller.
 *
 * The record length indicator needs to be stored in big-endian order.
 *
 * @return a pointer to a \c BDBuffer holding the encrypted password
 * record. The memory occupied by the buffer has to be freed by the
 * caller of the method. It returns \c NULL when the end of file has
 * been reached.
 */
BDBuffer*
File::read() const throw (YAPETException) {
    uint32_t len;
    int retval = ::read (fd, &len, sizeof (uint32_t) );

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if (retval == 0)
        return NULL;

    if ( ( (size_t) retval) < sizeof (uint32_t) )
        throw YAPETException (_ ("Short read on file: ") + filename);

    // Convert len to the endianess of the architecture
    len = int_from_disk<uint32_t> (len);
    BDBuffer* buf = new BDBuffer (len);
    retval = ::read (fd, *buf, len);

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if (retval == 0) {
        delete buf;
        return NULL;
    }

    if ( ( (uint32_t) retval) < len) {
        delete buf;
        throw YAPETException (_ ("Short read on file: ") + filename);
    }

    return buf;
}

/**
 * Writes the supplied \c BDBuffer to disk. It writes in front of the
 * \c BDBuffer its length. The length is stored in big-endian order.
 *
 * @param buff reference to a \c BDBuffer holding the encrypted data
 * to write
 *
 * @param forceappend if this flag is set to \c true, the method first
 * seeks to the end of the file, if set to \c false, it writes at the
 * position the file pointer points to.
 *
 * @param forcewrite before writing any data, the method checks
 * whether the last modification date stored in \c mtime matches the
 * date returned by \c lastModified(). If they differ, and this flag
 * is set to \c false, the write operation will fail and an exception
 * is thrown. If the flag is set to \c true, it writes the data to the
 * file regardless of the last modification date.
 *
 * @throw YAPETRetryException if the file has been externally modified
 * (outside of this class), and \c forcewrite is not \c true, this
 * exception is thrown.
 */
void
File::write (const BDBuffer& buff, bool forceappend, bool forcewrite)
throw (YAPETException, YAPETRetryException) {
    if ( (mtime != lastModified() ) && !forcewrite)
        throw YAPETRetryException (_ ("File has been modified") );

    if (forceappend) {
        off_t pos = lseek (fd, 0, SEEK_END);

        if ( ( (off_t) - 1) == pos)
            throw YAPETException (strerror (errno) );
    }

    uint32_t s = buff.size();
    // Convert s to the on-disk structure
    s = int_to_disk<uint32_t> (s);
    int retval = ::write (fd, &s, sizeof (uint32_t) );

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if (retval != sizeof (uint32_t) )
        throw YAPETException (_ ("Short write on file: ") + filename);

    retval = ::write (fd, buff, buff.size() );

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if ( ( (size_t) retval) < buff.size() )
        throw YAPETException (_ ("Short write on file: ") + filename);

    mtime = lastModified();
}

/**
 * Indicates whether or not the file specified by \c fd is empty.
 *
 * @return \c true if the file's size is zero, \c false otherwise.
 */
bool
File::isempty() const throw (YAPETException) {
    struct stat st_buf;
    int retval = fstat (fd, &st_buf);

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if (st_buf.st_size == 0)
        return true;

    return false;
}

/**
 * Modified in version 0.6.
 *
 * As of version 0.6, creates a header struct \c FileHeader_64 and calls \c writeHeader. It
 * then reads and decrypts the header in order to verify.
 *
 * @param key reference to the key used to encrypt the header.
 */
void
File::initFile (const Key& key) throw (YAPETException) {
    Crypt crypt (key);
    Record<FileHeader_64> header;
    FileHeader_64* ptr = header;
    ptr->version = VERSION_2;
    memcpy (ptr->control, CONTROL_STR, HEADER_CONTROL_SIZE);
    ptr->pwset = int_to_disk<int64_t> (time (NULL) );
    mtime = lastModified();
    writeHeader (header, key);
    // Sanity checks
    BDBuffer* buff = readHeader();

    if (buff == NULL)
        throw YAPETException (_ ("EOF encountered while reading header") );

    Record<FileHeader_64>* dec_hdr = crypt.decrypt<FileHeader_64> (*buff);
    FileHeader_64* ptr_dec_hdr = *dec_hdr;
    int retval = memcmp (ptr_dec_hdr->control, ptr->control, HEADER_CONTROL_SIZE);

    if (retval != 0)
        throw YAPETException (_ ("Sanity check for control field failed") );

    delete buff;
    delete dec_hdr;
}

/**
 * Modified in version 0.6.
 *
 * Encrypts and writes the file header provided to the file.
 *
 * Since version 0.6 it expects by default a FileHeader_64 header.
 *
 * @param header a reference to the header. It will be encrypted using
 * the key provided.
 *
 * @param key the key used to encrypt the header provided.
 */
void
File::writeHeader (const Record<FileHeader_64>& header, const Key& key)
throw (YAPETException) {
    Crypt crypt (key);
    BDBuffer* buff = NULL;

    try {
        buff = crypt.encrypt (header);
        writeHeader (*buff);
    } catch (YAPETException& ex) {
        if (buff != NULL)
            delete buff;

        throw;
    } catch (...) {
        if (buff != NULL)
            delete buff;

        throw YAPETException (_ ("Unknown exception catched") );
    }

    delete buff;
}

/**
 * Writes the recognition string at the beginning of the file and
 * eventually the provided header \c enc_header
 *
 * @param enc_header reference to a BDBuffer holding the encrypted
 * header
 */
void
File::writeHeader (const BDBuffer& enc_header) throw (YAPETException) {
    seekAbs (0);
    // Write the recognition string
    ssize_t retval = ::write (fd, RECOG_STR, strlen (RECOG_STR) );

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if ( ( (size_t) retval) != strlen (RECOG_STR) )
        throw YAPETException (_ ("Short write on file: ") + filename);

    mtime = lastModified();
    write (enc_header);
}

/**
 * Reads the encrypted header from the file. It also checks whether or
 * not the file is of the expected type by reading the recognition
 * string. If the string read does not match the one predefined, it
 * throws an \c YAPETException.
 *
 * The memory occupied by the \c BDBuffer returned has to be freed by
 * the caller.
 *
 * @return pointer to a \c BDBuffer holding the encrypted file
 * header. The memory occupied has to be freed by the caller.
 */
BDBuffer*
File::readHeader() const throw (YAPETException) {
    seekAbs (0);
    char* buff = (char*) alloca (strlen (RECOG_STR) );

    if (buff == NULL)
        throw YAPETException (_ ("Memory exhausted") );

    int retval = ::read (fd, buff, strlen (RECOG_STR) );

    if (retval == -1)
        throw YAPETException (strerror (errno) );

    if ( ( (size_t) retval) != strlen (RECOG_STR) )
        throw YAPETException (_ ("File type not recognized") );

    retval = memcmp (RECOG_STR, buff, strlen (RECOG_STR) );

    if (retval != 0)
        throw YAPETException (_ ("File type not recognized") );

    return read();
}

/**
 * New in version 0.6.
 *
 * It returns the header decrypted. The caller have to check the pointers
 * returned for null values in order to determine which header to use, e.g.
 *
 @verbatim
 if (ptr32 != NULL) {
    // do something
 } else if (ptr64 != NULL) {
    // do something
 } else {
    // error
 }
 @endverbatim
 *
 * The memory allocated by the method for the records have to be freed by the
 * caller.
 *
 * @param key reference to a Key object used to decrypt the header.
 *
 * @param ptr32 the 32bit header record. If the yapet file does not contain a
 * FileHeader_32, NULL is returned.
 *
 * @param ptr64 the 64bit header record. If the yapet file does not contain a
 * FileHeader_64, NULL is returned.
 */
void
File::readHeader(const Key& key, Record<FileHeader_32>** ptr32, Record<FileHeader_64>** ptr64) const throw(YAPETException) {
    assert(ptr32 != NULL && ptr64 != NULL);
    if (ptr32 == NULL)
	throw YAPETException(_("Null pointer passed in ptr32"), NULLPOINTER);
    if (ptr64 == NULL)
	throw YAPETException(_("Null pointer passed in ptr64"), NULLPOINTER);

    Crypt crypt (key);
    BDBuffer* enc_header = NULL;

    try {
        enc_header = readHeader();
	// First try to read a 32bit header
	try {
	    *ptr32 = crypt.decrypt<FileHeader_32> (*enc_header);
	} catch (YAPETException& ex) {

	    if (*ptr32 != NULL) {
		delete *ptr32;
		*ptr32 = NULL;
	    }

	    try {
		*ptr64 = crypt.decrypt<FileHeader_64> (*enc_header);
	    } catch (YAPETEncryptionException& ex) { // Catch invalid password
		if (enc_header != NULL) {
		    delete enc_header;
		    enc_header = NULL;
		}
		
		if (*ptr32 != NULL) {
		    delete *ptr32;
		    *ptr32 = NULL;
		}
		if (*ptr64 != NULL) {
		    delete *ptr64;
		    *ptr64 = NULL;
		}
		
		throw YAPETInvalidPasswordException();
	    } catch (YAPETException &ex) {
		// Ok, we got another problem
		if (*ptr64 != NULL) {
		    delete *ptr64;
		    *ptr64 = NULL;
		}
		throw;
	    }
	}
    } catch (YAPETEncryptionException& ex) { // Catch invalid password
        if (enc_header != NULL) delete enc_header;

        if (*ptr32 != NULL) {
	    delete *ptr32;
	    *ptr32 = NULL;
	}
	if (*ptr64 != NULL) {
	    delete *ptr64;
	    *ptr64 = NULL;
	}

        throw YAPETInvalidPasswordException();
    } catch (YAPETException& ex) {
        if (enc_header != NULL) delete enc_header;

        if (*ptr32 != NULL) {
	    delete *ptr32;
	    *ptr32 = NULL;
	}
	if (*ptr64 != NULL) {
	    delete *ptr64;
	    *ptr64 = NULL;
	}

        throw;
    }

    delete enc_header;
}

/**
 * Modified in version 0.6
 *
 * Validates the key provided by reading the file header, decrypting
 * it and comparing the control string of the file header with the
 * string \c RECOG_STR. If those operations succeed, the key is
 * considered valid. In case of an error, an exception is thrown.
 *
 * Since this method relies on \c readHeader(), the file type is
 * checked automatically.
 *
 * @param key the key to validate against the file.
 */
void
File::validateKey (const Key& key)
throw (YAPETException, YAPETInvalidPasswordException) {
    // Expect either a 32bit or 64bit header
    Record<FileHeader_32>* dec_header_32 = NULL;
    Record<FileHeader_64>* dec_header_64 = NULL;

    readHeader(key, &dec_header_32, &dec_header_64);
    assert(dec_header_32 != NULL || dec_header_64 != NULL);

    FileHeader_32* ptr_dec_header_32 = 
	(dec_header_32 != NULL) ? static_cast<FileHeader_32*>(*dec_header_32) : NULL;
    FileHeader_64* ptr_dec_header_64 = 
	(dec_header_64 != NULL) ? static_cast<FileHeader_64*>(*dec_header_64) : NULL;

    int retval;
    if (ptr_dec_header_32 != NULL) {
	retval = memcmp (ptr_dec_header_32->control,
                         CONTROL_STR,
                         HEADER_CONTROL_SIZE);
    } else {
	assert(ptr_dec_header_64 != NULL);
	retval = memcmp (ptr_dec_header_64->control,
                         CONTROL_STR,
                         HEADER_CONTROL_SIZE);
    }
    if (dec_header_32 != NULL)
	delete dec_header_32;
    if (dec_header_64 != NULL)
	delete dec_header_64;

    if (retval != 0)
        throw YAPETInvalidPasswordException();
}

/**
 * Opens the file specified. Optionally creates the file if it does
 * not exist and \c create is set \c true.
 *
 * When opening an existing file, the key provided is validated. When
 * creating a new file, the key is used to encrypt the header.
 *
 * The file opened or created will stay open as long as the instance
 * of this class exists. There is no method for closing the file. Only
 * the destructor closes the file.
 *
 * @param fn string holding the file name
 *
 * @param key the key used for verification or encrypting the file
 * header
 *
 * @param create flag indicating whether the file should be created
 * (\c true) or just opened (\c false). Be aware that passing \c true
 * to this flag always causes the file to be created. Even if it
 * already exists. Existing files will be truncated and the data
 * stored will be lost.
 *
 * @param secure if \c true, the functions checks whether or not the file
 * permissions are secure. If \c false, file permissions are not checked for
 * security. When creating a file and the value is \c true, the file is created
 * using secure file permissions meaning only the owner has write and read
 * access. Else, the owner has read and write access, the group and world has
 * read access.
 */
File::File (const std::string& fn, const Key& key, bool create, bool secure)
throw (YAPETException) : filename (fn), usefsecurity (secure) {
    if (create)
        openCreate();
    else
        openNoCreate();

    if (isempty() ) {
        initFile (key);
    } else {
        validateKey (key);
    }
}

/**
 * Duplicates the file descriptor by calling \c dup().
 */
File::File (const File& f) throw (YAPETException) {
    fd = dup (f.fd);

    if (fd == -1)
        throw YAPETException (strerror (errno) );

    filename = f.filename;
    mtime = f.mtime;
    usefsecurity = f.usefsecurity;
}

/**
 * Closes the file.
 */
File::~File() {
    close (fd);
}

/**
 * Stores the list of \c PartDec records in the file.
 *
 * @param records list of \c PartDec records
 *
 * @sa PartDec
 */
void
File::save (std::list<PartDec>& records) throw (YAPETException) {
    if (usefsecurity)
        setFileSecurity();

    preparePWSave();
    std::list<PartDec>::iterator it = records.begin();

    while (it != records.end() ) {
        write ( it->getEncRecord() );
        it++;
    }
}

/**
 * Reads the stored records from the file using the key provided and
 * returns a list holding the partially decrypted records. If the file
 * has no records stored, it returns an empty list.
 *
 * @param key the key used to decrypt the records. It has to be same
 * key that was used to encrypt the records, of course.
 *
 * @return a list holding the partially decrypted records. Or an empty
 * list if no records are stored in the file
 *
 * @sa PartDec
 */
std::list<PartDec>
File::read (const Key& key) const throw (YAPETException) {
    seekDataSection();
    BDBuffer* buff = NULL;
    std::list<PartDec> retval;

    try {
        buff = read();

        while (buff != NULL) {
            retval.push_back (PartDec (*buff, key) );
            delete buff;
            buff = read();
        }
    } catch (YAPETException& ex) {
        if (buff != NULL)
            delete buff;

        throw;
    }

    return retval;
}

/**
 * Uses a new key to encrypt the records in the file. The records
 * stored in the file are decrypted using the old key and then
 * encrypted using the new key.
 *
 * Before performing this operation, it renames the file encrypted
 * with the old key to 'filename + ".bak"'. It then reads the data
 * from this file and writes it to the newly created file named
 * 'filename'.
 *
 * @param oldkey the old key used to encrypt the records
 *
 * @param newkey the new key used to encrypt the records
 */
void
File::setNewKey (const Key& oldkey,
                 const Key& newkey) throw (YAPETException) {
    close (fd);
    std::string backupfilename (filename + ".bak");
    int retval = rename (filename.c_str(), backupfilename.c_str() );

    if (retval == -1) {
        // Reopen the old file
        openNoCreate();
        throw YAPETException (strerror (errno) );
    }

    File* oldfile = NULL;

    try {
        // Reopen the old (backup) file
        oldfile = new File (backupfilename, oldkey, false, false);
        // Initialize the (this) file with the new key
        openCreate();
        initFile (newkey);
        // Retrieve the records encrypted with the old key
        std::list<PartDec> entries = oldfile->read (oldkey);
        std::list<PartDec>::iterator it = entries.begin();
        Crypt oldcrypt (oldkey);
        Crypt newcrypt (newkey);

        while (it != entries.end() ) {
            Record<PasswordRecord>* dec_rec_ptr = NULL;
            BDBuffer* new_enc_rec = NULL;

            try {
                // Decrypt with the old key
                const BDBuffer old_enc_rec = (*it).getEncRecord();
                dec_rec_ptr =
                    oldcrypt.decrypt<PasswordRecord> (old_enc_rec);
                new_enc_rec =
                    newcrypt.encrypt (*dec_rec_ptr);
                write (*new_enc_rec);
                delete dec_rec_ptr;
                delete new_enc_rec;
            } catch (YAPETException& ex) {
                if (dec_rec_ptr != NULL)
                    delete dec_rec_ptr;

                if (new_enc_rec != NULL)
                    delete new_enc_rec;

                throw;
            }

            it++;
        }
    } catch (YAPETException& ex) {
        if (oldfile != NULL)
            delete oldfile;

        throw;
    }

    delete oldfile;
}

/**
 * Modified in version 0.6.
 *
 * Returns the time as a \c uint64_t when the master password was set.
 *
 * @param key the key used to decrypt the header.
 *
 * @return a \c uint64_t representing the time the master password was
 * set.
 */
int64_t
File::getMasterPWSet (const Key& key) const
throw (YAPETException, YAPETInvalidPasswordException) {
    // Expect either a 32bit or 64bit header
    Record<FileHeader_32>* dec_header_32 = NULL;
    Record<FileHeader_64>* dec_header_64 = NULL;

    readHeader(key, &dec_header_32, &dec_header_64);
    assert(dec_header_32 != NULL || dec_header_64 != NULL);

    FileHeader_32* ptr_dec_header_32 = 
	(dec_header_32 != NULL) ? static_cast<FileHeader_32*>(*dec_header_32) : NULL;
    FileHeader_64* ptr_dec_header_64 = 
	(dec_header_64 != NULL) ? static_cast<FileHeader_64*>(*dec_header_64) : NULL;

    int64_t t;
    if (ptr_dec_header_32 != NULL) {
	t = int_from_disk<int32_t> (ptr_dec_header_32->pwset);
    } else {
	assert(ptr_dec_header_64 != NULL);
	t = int_from_disk<int64_t> (ptr_dec_header_64->pwset);
    }

    if (dec_header_32 != NULL)
	delete dec_header_32;
    if (dec_header_64 != NULL)
	delete dec_header_64;

    return t;
}

/**
 * New since version 0.6.
 *
 * Return the file version.
 */
FILE_VERSION
File::getFileVersion(const Key& key) const throw (YAPETException, YAPETInvalidPasswordException) {
    // Expect either a 32bit or 64bit header
    Record<FileHeader_32>* dec_header_32 = NULL;
    Record<FileHeader_64>* dec_header_64 = NULL;

    readHeader(key, &dec_header_32, &dec_header_64);
    assert(dec_header_32 != NULL || dec_header_64 != NULL);

    FileHeader_32* ptr_dec_header_32 = 
	(dec_header_32 != NULL) ? static_cast<FileHeader_32*>(*dec_header_32) : NULL;
    FileHeader_64* ptr_dec_header_64 = 
	(dec_header_64 != NULL) ? static_cast<FileHeader_64*>(*dec_header_64) : NULL;

    FILE_VERSION v;
    if (ptr_dec_header_32 != NULL) {
	v = static_cast<FILE_VERSION>(ptr_dec_header_32->version);
    } else {
	assert(ptr_dec_header_64 != NULL);
	v = static_cast<FILE_VERSION>(ptr_dec_header_64->version);
    }

    if (dec_header_32 != NULL)
	delete dec_header_32;
    if (dec_header_64 != NULL)
	delete dec_header_64;

    return v;
}

const File&
File::operator= (const File & f) throw (YAPETException) {
    if (this == &f) return *this;

    close (fd);
    fd = dup (f.fd);

    if (fd == -1)
        throw YAPETException (strerror (errno) );

    filename = f.filename;
    return *this;
}