-
Notifications
You must be signed in to change notification settings - Fork 6
/
files.pas
4002 lines (3695 loc) · 107 KB
/
files.pas
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
unit Files;
{$mode objfpc}{$H+}
{$define DEBUG}
{$define BTree}
{$define Blowfish}
{$define IDEA}
interface
{ TODO : Need a memory file handle for temporary files }
{ TODO : A flat record file handle }
uses
Classes, SysUtils, Logging, Crypto, DCPcrypt2;
const
PAGE_SIZE = 4096; // Must be multiple of 128 for encryption to work
DEFAULT_VERSION = 1;
MAX_FREE_PAGES = 128;
MAX_FILE_COUNT = 256;
MAX_META_PAGES = 256;
MAX_META_SIZE = MAX_META_PAGES * PAGE_SIZE;
MAX_FAT_PAGE_ENTRIES = PAGE_SIZE div 4 - 1;
DEFAULT_PACK_ITERATIONS = 32;
IMPORT_EXPORT_CHUNK_SIZE = 65536 * 2; // Size of Import/Export memory buffer
MIN_PROGRESS_SIZE = 1024 * 1024 * 4; // Importing/Exporting files larger than this will trigger OnProgress event
PAGEMAP_HEADER = -MaxSmallInt;
PAGEMAP_META = -MaxSmallInt + 1;
PAGEMAP_FREE = -MaxSmallInt + 2;
KEY_ENCRYPTION_CIPHER = caRijndael; // Must accept a 256 bit key
KEY_ENCRYPTION_MODE = cmCBC;
KEY_ENCRYPTION_HASH = haHaval256; // Must use a 256 bit hash function
PASSWORD_HASH = haSHA1; // Must be > 128 bits and different from encryption hash
type
TPageNum = Cardinal;
TPageIndex = Cardinal;
TFileDigest = TBlock128;
TFileKey = TBlock256;
{ TFileHeader }
TFileHeader = packed record { Size must = PAGE_SIZE }
// First 64 bytes are not encrypted (except for the Key)
Version : Byte; //1
Cipher : TCipherAlgorithm; //1
Hash : THashAlgorithm; //1
Unused1 : array[1..16-3] of Byte;
Digest : TFileDigest; //16
Key : TFileKey; //32
//
FreePageCount : 0..MAX_FREE_PAGES;
MetaSize : 0..MAX_META_SIZE;
FreePages : array[1..MAX_FREE_PAGES] of TPageNum;
MetaPages : array[1..MAX_META_PAGES] of TPageNum;
FATPages : array[1..MAX_FILE_COUNT] of TPageNum;
FileSize : array[1..MAX_FILE_COUNT] of TPageNum;
Unused2 : array[1..443] of Byte;
end;
PFileHeader = ^TFileHeader;
{ TFATPage }
TFATPage = record
Pages: array[0..MAX_FAT_PAGE_ENTRIES - 1] of TPageNum;
Next: TPageNum;
end;
PFATPage = ^TFATPage;
{ TBufferedPage }
TBufferedPage = packed record
PageNum: Cardinal;
PageIdx: Cardinal;
FileID: Byte;
RefCount: Word;
Modified: Boolean;
Data: Pointer;
end;
PBufferedPage = ^TBufferedPage;
// Forward Declarations
TFileContainer = class;
TFileMetadata = class;
TFile = class;
TCustomFileHandle = class;
// Exceptions
EFileError = class(Exception);
// Events
TFileOperation = (foNone, foImport, foExport, foDelete, foDefrag, foEncrypt, foDecrypt);
TFileProgressEvent = procedure (Sender: TObject; Operation: TFileOperation; Name: String; Position, Size: Integer) of object;
TMetadataEvent = procedure (Sender: TObject; Stream: TStream) of object;
TFilePasswordEvent = procedure (Sender: TObject; var Password: String) of object;
{ TFileBuffer }
TBufferMode = (bmSequential, bmRandomAccess);
TFileBuffer = class(TObject)
private
FContainer : TFileContainer;
FFile : TFile;
FArray : array of PBufferedPage;
FCount : Integer;
FSize : Integer;
FMode : TBufferMode;
function GetPage(Index: Integer): PBufferedPage;
procedure Delete(Index: Integer);
function BinSearch(PageIdx: TPageIndex; var Location: Integer): Boolean;
procedure Clear;
function PageNumChanged(OldPageNum, NewPageNum: TPageNum): Boolean;
procedure PageNumSwapped(PageNum1, PageNum2: TPageNum);
procedure CheckOrder;
procedure CheckRange;
procedure DeleteUnusedBuffers;
procedure SaveModifiedPages;
public
constructor Create(AFile: TFile);
destructor Destroy; override;
function Search(PageIdx: TPageIndex): PBufferedPage;
function Insert(Page: PBufferedPage): Boolean;
function Remove(PageIdx: TPageIndex): Boolean;
procedure Truncate(PageIdx: TPageIndex);
procedure Flush;
procedure Validate;
property Count: Integer read FCount;
property Pages[Index: Integer]: PBufferedPage read GetPage; default;
property Mode: TBufferMode read FMode write FMode;
end;
{ TFileFAT }
TFileFAT = class(TObject)
private
FContainer : TFileContainer;
FFile : TFile;
FPages : array of PBufferedPage;
FSize : Integer;
FFATPageCount : TPageIndex;
FFilePageCount : TPageIndex;
FLoaded : Boolean;
function CountZeroPages: Integer;
function GetItem(Index: TPageIndex): TPageNum;
procedure SetItem(Index: TPageIndex; AValue: TPageNum);
function GetFATPage(Index: Integer): PBufferedPage;
procedure PageNumSwapped(PageNum1, PageNum2: TPageNum);
function PageNumChanged(OldPageNum, NewPageNum: TPageNum): Boolean;
procedure Fetch;
procedure Release;
function FindEmptyPage(var PageIdx: TPageIndex): Boolean;
protected
property FATPages[Index: Integer]: PBufferedPage read GetFATPage;
property FATPageCount: TPageIndex read FFATPageCount;
procedure RemoveTrailingZeros;
public
constructor Create(AFile: TFile);
destructor Destroy; override;
//
procedure Push(PageNum: TPageNum);
procedure Pop;
procedure Insert(PageIdx: TPageIndex; Value: TPageNum);
procedure Delete(PageIdx: TPageIndex);
procedure Flush;
//
property Items[Index: TPageIndex]: TPageNum read GetItem; default;
property Count: TPageIndex read FFilePageCount;
end;
{ TFileHandles }
TFileHandles = class(TObject)
private
FArray : array of TCustomFileHandle;
FSize : Integer;
FCount : Integer;
function BinSearch(Handle: TCustomFileHandle; var Location: Integer): Boolean;
procedure Delete(Location: Integer);
function GetItem(Index: Integer): TCustomFileHandle;
procedure InsertAt(Handle: TCustomFileHandle; Location: Integer);
function Search(Handle: TCustomFileHandle): Integer;
protected
procedure NotifyRootChanged;
procedure NotifySizeChanged;
procedure NotifyDelete(PageIdx: TPageIndex);
public
destructor Destroy; override;
procedure Insert(Handle: TCustomFileHandle);
procedure Remove(Handle: TCustomFileHandle);
procedure Close;
property Count: Integer read FCount;
property Items[Index: Integer]: TCustomFileHandle read GetItem; default;
end;
{ TFile }
{$Z1}
TFileKind = (fkStream, fkPage, {$IFDEF btree}fkBTree, {$ENDIF}fkTable); // TODO: fkTable
TFile = class(TLogObject)
private
FContainer : TFileContainer;
FFAT : TFileFAT;
FHandles : TFileHandles;
FBuffer : TFileBuffer;
FName : String;
FID : Byte;
FKind : TFileKind;
FRootNode : TPageIndex;
FRecordCount : Cardinal;
FRecordSize : Word;
//
procedure PageNumSwapped(PageNum1, PageNum2: TPageNum);
procedure SetKind(AValue: TFileKind);
procedure SetName(AValue: String);
procedure SetRecordCount(AValue: Cardinal);
procedure SetRecordSize(AValue: Word);
procedure SetRootNode(AValue: TPageIndex);
function GetPageCount: Cardinal;
function GetSize: Cardinal;
//
function PageNumChanged(OldPageNum, NewPageNum: TPageNum): Boolean;
//
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
procedure MetadataChanged;
protected
procedure SetSize(const AValue: Cardinal);
//
function Alloc: PBufferedPage;
function Fetch(PageIdx: TPageIndex): PBufferedPage;
procedure Release(var Page: PBufferedPage);
//
function Insert(PageIdx: TPageIndex): PBufferedPage;
procedure Delete(PageIdx: TPageIndex);
procedure Truncate(PageIdx: TPageIndex);
//
property FAT: TFileFAT read FFAT;
property Buffer: TFileBuffer read FBuffer;
public
constructor Create(AContainer: TFileContainer; AName: String; AID: Byte; AKind: TFileKind = fkStream);
constructor CreateFromStream(AContainer: TFileContainer; Stream: TStream);
destructor Destroy; override;
//
function CreateHandle(AKind: TFileKind): TCustomFileHandle;
procedure Flush;
procedure Delete;
//
property Size: Cardinal read GetSize;
property ID: Byte read FID;
property Name: String read FName write SetName;
property Kind: TFileKind read FKind write SetKind;
property RootNode: TPageIndex read FRootNode write SetRootNode;
property RecordCount: Cardinal read FRecordCount write SetRecordCount;
property RecordSize: Word read FRecordSize write SetRecordSize;
property PageCount: Cardinal read GetPageCount;
property Handles: TFileHandles read FHandles;
end;
{ TFiles }
TFiles = class(TObject)
private
FContainer: TFileContainer;
FArray: array of TFile;
FSize: Integer;
FCount: SmallInt;
function GetItem(Index: Integer): TFile;
function BinSearch(Name: String; var Location: Integer): Boolean;
procedure InsertAt(AFile: TFile; Location: Integer);
procedure Delete(AFile: TFile);
procedure Delete(Location: Integer);
function PageNumChanged(OldPageNum, NewPageNum: Cardinal): Boolean;
procedure PageNumSwapped(PageNum1, PageNum2: TPageNum);
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
protected
function GetID: Byte;
function Insert(Name: String; ID: Byte; Kind: TFileKind): TFile; overload;
function Insert(AFile: TFile): Integer; overload;
function Remove(Name: String): Boolean; overload;
function Remove(AFile: TFile): Boolean; overload;
function Remove(AID: Byte): Boolean; overload;
procedure Rename(OldName, NewName: String);
procedure Clear;
procedure MetadataChanged;
procedure CloseHandles;
public
destructor Destroy; override;
procedure Flush;
function Find(ID: Byte): Integer; overload;
function Find(Name: String): TFile; overload;
function Find(AFile: TFile): Integer; overload;
property Count: SmallInt read FCount;
property Items[Index: Integer]: TFile read GetItem; default;
end;
{ TCustomFileHandle }
TCustomFileHandle = class(TLogObject)
private
FContainer : TFileContainer;
FFile : TFile;
function GetID: Byte;
function GetPageCount: Cardinal;
function GetSize: Cardinal;
protected
FLast : PBufferedPage;
procedure SetSize(const AValue: Cardinal);
procedure SizeChanged; virtual;
procedure ReleaseBuffer; virtual;
procedure DeleteNotification(PageIdx: TPageIndex); virtual;
public
constructor Create(AFile: TFile); virtual;
destructor Destroy; override;
//
procedure Flush; virtual;
//
property Container: TFileContainer read FContainer;
property _File: TFile read FFile;
property ID: Byte read GetID;
property Size: Cardinal read GetSize;
property PageCount: Cardinal read GetPageCount;
end;
{ TPageFileHandle }
TPageFileHandle = class(TCustomFileHandle)
public
constructor Create(AFile: TFile); override;
function Fetch(PageIdx: TPageIndex): PBufferedPage;
procedure Release(var Page: PBufferedPage);
function Alloc: PBufferedPage;
procedure Truncate(PageIdx: TPageIndex);
function Insert(PageIdx: TPageIndex): PBufferedPage;
procedure Delete(PageIdx: TPageIndex); overload;
procedure Delete(var Page: PBufferedPage); overload;
end;
{ TStreamFileHandle }
TStreamFileHandle = class(TCustomFileHandle)
private
FPosition: Cardinal;
protected
procedure SizeChanged; override;
public
function Read(var Buffer; Count: Integer): Integer; overload;
function Read(Length: Integer): String; overload;
function Write(const Buffer; Count: Integer): Integer; overload;
function Write(Str: String): Integer; overload;
procedure Seek(Position: Cardinal);
procedure Truncate(Position: Cardinal);
property Position: Cardinal read FPosition write Seek;
end;
{ TFreePages }
TFreePages = class(TObject)
private
FContainer: TFileContainer;
function GetCount: Integer;
function GetItem(Index: Integer): TPageNum;
function BinSearch(Key: TPageNum; var Location: Integer): Boolean;
procedure InsertAt(PageNum: TPageNum; Location: Integer);
procedure DeleteAt(Location: Integer);
function PageNumChanged(OldPageNum, NewPageNum: TPageNum): Boolean;
procedure PageNumSwapped(PageNum1, PageNum2: TPageNum);
public
procedure Insert(PageNum: TPageNum);
function Remove(PageNum: TPageNum): Boolean;
procedure Truncate(PageNum: TPageNum);
function GetLowest: TPageNum;
function CheckOrder: Boolean;
property Count: Integer read GetCount;
property Items[Index: Integer]: TPageNum read GetItem; default;
end;
{ TPageMap }
// Values are a PAGEMAP_ constant or:
// if Value is positive it's a fileid,
// if -ve then it's a FAT page for the fileid.
// If zero then the page has been lost track of and it's an error.
TPageMap = class(TLogObject)
private
FContainer: TFileContainer;
FArray : array of SmallInt;
FCount : Integer;
FResult: Boolean;
function GetPage(PageNum: TPageNum): SmallInt;
procedure SetPage(PageNum: TPageNum; AValue: SmallInt);
procedure SetCount(AValue: Integer);
procedure Clear;
public
constructor Create(Container: TFileContainer);
destructor Destroy; override;
procedure Build;
function Validate: Boolean;
property Count: Integer read FCount write SetCount;
property Values[PageNum: TPageNum]: SmallInt read GetPage write SetPage;
end;
{ TFileMetadata }
TFileMetadata = class(TLogObject)
private
FContainer: TFileContainer;
FChanged: Boolean;
function GetSize: Cardinal;
function GetPage(Index: Integer): TPageNum;
function GetPageCount: Integer;
function PageNumChanged(OldPageNum, NewPageNum: TPageNum): Boolean;
procedure PageNumSwapped(PageNum1, PageNum2: TPageNum);
protected
procedure SaveFromStream(Stream: TStream);
procedure LoadToStream(Stream: TStream);
public
constructor Create;
property Pages[Index: Integer]: TPageNum read GetPage;
property PageCount: Integer read GetPageCount;
property Size: Cardinal read GetSize;
property Changed: Boolean read FChanged write FChanged;
end;
{ TBasicPageFile }
{TBasicPageFile = class(TLogObject)
private
FActive: Boolean;
FFilename: String;
FHandle: TFileHandle;
FPageCount: Integer;
FBuffer: PBufferedPage;
//
FBeforeOpen: TNotifyEvent;
FAfterOpen: TNotifyEvent;
FBeforeClose: TNotifyEvent;
FAfterClose: TNotifyEvent;
FOnReadData: TNotifyEvent;
FOnWriteData: TNotifyEvent;
protected
procedure Replace(Source, Target: TPageNum); virtual;
procedure Swap(PageNum1, PageNum2: TPageNum); virtual;
procedure Truncate(PageNum: TPageNum); virtual;
//
function Fetch(PageNum: TPageNum): PBufferedPage; virtual;
function Alloc: PBufferedPage; virtual;
function Release(var Page: PBufferedPage); virtual;
//
procedure ReadData(PageNum: TPageNum; var Data: Pointer); virtual;
procedure WriteData(PageNum: TPageNum; const Data: Pointer); virtual;
public
constructor Create;
destructor Destroy; override;
//
procedure Open; virtual;
procedure Close; virtual;
//
property Active: Boolean read FActive write SetActive;
property Filename: String read FFilename write SetFilename;
property Handle: TFileHandle read FHandle;
property PageCount: Cardinal read FPageCount;
end; }
{ TFileContainer }
TFileContainer = class(TLogObject)
private
FActive: Boolean;
FFilename: String;
FPageCount: Cardinal;
FAutoPack: Boolean;
FDeletingPage: TPageNum;
FPassword: String;
FCipher: TDCP_BlockCipher;
FKey: TFileKey;
FEncrypting: Boolean; // TODO: Get rid of this and use FOperation instead
FHandle: THandle;
FFreePages: TFreePages;
FMetadata: TFileMetadata;
FFiles: TFiles;
FPageMap: TPageMap;
FOperation: TFileOperation;
FOnProgress: TFileProgressEvent;
FOnLoadMetadata: TMetadataEvent;
FOnSaveMetadata: TMetadataEvent;
FOnGetPassword: TFilePasswordEvent;
//
function Login: Boolean;
function CheckPassword(AValue: String): Boolean;
procedure SetPassword(AValue: String);
function PasswordRequired: Boolean;
//
function GetCipherAlgorithm: TCipherAlgorithm;
function GetEncrypted: Boolean;
procedure GenerateCipherKey;
procedure InitCipherKey;
procedure LoadCipherKey;
procedure SaveCipherKey;
//
procedure DoProgress(AName: String; APosition, ASize: Cardinal);
function GetFileSize: Cardinal;
function GetVersion: Byte;
procedure Swap(Source, Target: PBufferedPage);
procedure NotifyPageSwap(PageNum1, PageNum2: TPageNum);
procedure SetActive(AValue: Boolean);
procedure CreateHeader;
procedure ReadHeader;
procedure WriteHeader;
procedure SaveMetadata;
procedure LoadMetadata;
//
procedure DeleteTrailingFreePages;
procedure Replace(Source, Target: TPageNum);
protected
FHeader: TFileHeader;
procedure ReadData(PageNum: TPageNum; Data: Pointer);
procedure WriteData(PageNum: TPageNum; Data: Pointer);
procedure Truncate(PageNum: TPageNum);
procedure Delete(PageNum: TPageNum); overload;
procedure Delete(var Page: PBufferedPage); overload;
procedure NotifyPageNumChanged(OldPageNum,NewPageNum: TPageNum);
procedure Release(var Page: PBufferedPage);
function Fetch(PageNum: TPageNum): PBufferedPage;
function Alloc: PBufferedPage;
procedure Dispose(var Page: PBufferedPage);
procedure EncryptPage(PageNum: Cardinal; Data: Pointer);
procedure DecryptPage(PageNum: Cardinal; Data: Pointer);
//
procedure ClearMetadata; virtual;
procedure DoLoadMetadata(Stream: TStream); virtual;
procedure DoSaveMetadata(Stream: TStream); virtual;
//
function BeginOperation(Operation: TFileOperation): Boolean;
procedure EndOperation;
//
property Cipher: TDCP_BlockCipher read FCipher;
public
constructor Create;
destructor Destroy; override;
procedure Open;
procedure Close;
function CreateFile(Filename: String; Kind: TFileKind = fkStream): TCustomFileHandle;
function OpenFile(Filename: String): TCustomFileHandle; overload;
function OpenFile(Filename: String; Kind: TFileKind): TCustomFileHandle; overload;
function FileExists(Filename: String): Boolean;
procedure RenameFile(OldName, NewName: String);
function DeleteFile(Filename: String): Boolean;
procedure ImportFile(Stream: TStream; Filename: String);
procedure ExportFile(Stream: TStream; Filename: String);
procedure Flush;
procedure Pack(MaxIterations: Byte = DEFAULT_PACK_ITERATIONS);
procedure Defrag;
procedure Encrypt(Password: String; Algorithm: TCipherAlgorithm = caTwofish);
procedure Decrypt;
//
property Active: Boolean read FActive write SetActive;
property AutoPack: Boolean read FAutoPack write FAutoPack;
property Encrypted: Boolean read GetEncrypted;
property CipherAlgorithm: TCipherAlgorithm read GetCipherAlgorithm;
property Filename: String read FFilename write FFilename;
property Password: String read FPassword write SetPassword;
property Version: Byte read GetVersion;
property Operation: TFileOperation read FOperation;
property PageCount: Cardinal read FPageCount;
property FileSize: Cardinal read GetFileSize;
property Files: TFiles read FFiles;
property OnLoadMetadata: TMetadataEvent read FOnLoadMetadata write FOnLoadMetadata;
property OnSaveMetadata: TMetadataEvent read FOnSaveMetadata write FOnSaveMetadata;
property OnProgress: TFileProgressEvent read FOnProgress write FOnProgress;
property OnGetPassword: TFilePasswordEvent read FOnGetPassword write FOnGetPassword;
// For Testing Purposes
{$IFDEF DEBUG}
procedure Validate;
procedure ValidateFreePages;
procedure ValidatePageMap;
procedure ValidateBuffers;
property FreePages: TFreePages read FFreePages;
property Header: TFileHeader read FHeader;
property Metadata: TFileMetadata read FMetadata;
property PageMap: TPageMap read FPageMap;
{$ENDIF}
end;
implementation
uses
{$IFDEF Unix}
BaseUnix,
{$ENDIF}
{$IFDEF Windows}
Windows,
{$ENDIF}
{$IFDEF btree}
btreefile,
{$ENDIF}
Rand,
ErrorMsg;
type
TByteArray = array[0..PAGE_SIZE] of Byte;
TBTreeHack = class(TBTreeFileHandle);
var
ZERO_DIGEST: TFileDigest = (0,0,0,0);
{ TPageMap }
constructor TPageMap.Create(Container: TFileContainer);
begin
inherited Create;
Log.Name := 'PageMap';
FContainer := Container;
{$IFDEF DEBUG}Log.Filter := [mtInfo,mtError,mtDebug];{$ELSE}Log.Filter := [mtInfo,mtError];{$ENDIF}
end;
destructor TPageMap.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TPageMap.Clear;
begin
SetLength(FArray,0);
FCount := 0;
end;
procedure TPageMap.Build;
var
X,Y: Integer;
PageNum: TPageNum;
F: TFile;
begin
Clear;
if FContainer.PageCount > 0 then
begin
// Set page count and zero array
Count := FContainer.PageCount;
for X := 0 to Count - 1 do
FArray[X] := 0;
// First page is always the file header
Values[0] := PAGEMAP_HEADER;
// Add free page list to the page map
for X := 1 to FContainer.FreePages.Count do
begin
PageNum := FContainer.FreePages[X];
if PageNum < Count then // Free page list might contain pages beyond end of file
Values[PageNum] := PAGEMAP_FREE;
end;
// Add Meta Pages
for X := 1 to FContainer.Metadata.PageCount do
Values[FContainer.Metadata.Pages[X]] := PAGEMAP_META;
// Add FAT Pages
for X := 0 to FContainer.Files.Count - 1 do
begin
F := FContainer.Files[X];
for Y := 0 to F.FAT.Count - 1 do
Values[F.FAT.Items[Y]] := X+1;
for Y := 0 to F.FAT.FATPageCount - 1 do
Values[F.FAT.FATPages[Y]^.PageNum] := -X - 1;
end;
end;
end;
function TPageMap.Validate: Boolean;
var
X: Integer;
begin
FResult := True;
for X := 0 to FCount - 1 do
if FArray[X] = 0 then
begin
FResult := False;
Log.Send(mtError,'Pagemap Validation Failure: Lost track of page %d',[X]);
end;
Result := FResult;
end;
function TPageMap.GetPage(PageNum: TPageNum): SmallInt;
begin
Assert(PageNum < FCount);
Result := FArray[PageNum];
end;
procedure TPageMap.SetPage(PageNum: TPageNum; AValue: SmallInt);
begin
Assert(PageNum < FCount);
Assert(FArray <> nil);
if FArray[PageNum] <> 0 then
begin
FResult := False;
Log.Send(mtError,'Pagemap Validation Failure: Page %d is in two places',[PageNum]);
end;
FArray[PageNum] := AValue;
end;
procedure TPageMap.SetCount(AValue: Integer);
begin
if FCount=AValue then Exit;
FCount:=AValue;
SetLength(FArray,FCount);
end;
{ TFiles }
destructor TFiles.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TFiles.Clear;
var
I: Integer;
begin
CloseHandles;
for I := FCount - 1 downto 0 do
FArray[I].Destroy;
SetLength(FArray,0);
FSize := 0;
FCount := 0;
end;
procedure TFiles.MetadataChanged;
begin
FContainer.FMetadata.FChanged := True;
end;
procedure TFiles.LoadFromStream(Stream: TStream);
var
I: Integer;
C: SmallInt;
S: Integer;
begin
Clear;
S := Stream.Size - Stream.Position;
if S >= SizeOf(C) then
Stream.Read(C,SizeOf(C))
else
C := 0;
for I := 0 to C - 1 do
TFile.CreateFromStream(FContainer,Stream);
end;
procedure TFiles.SaveToStream(Stream: TStream);
var
I: Integer;
begin
Stream.Position := 0;
Stream.Write(FCount,SizeOf(FCount));
for I := 0 to FCount - 1 do
FArray[I].SaveToStream(Stream);
end;
function TFiles.Find(Name: String): TFile;
var
Location: Integer;
begin
if BinSearch(Name,Location) then
Result := FArray[Location]
else
Result := nil;
end;
function TFiles.Find(ID: Byte): Integer;
begin
for Result := 0 to FCount - 1 do
if FArray[Result].ID = ID then Exit;
Result := -1;
end;
function TFiles.Find(AFile: TFile): Integer;
begin
for Result := 0 to FCount - 1 do
if FArray[Result] = AFile then Exit;
Result := -1;
end;
function TFiles.BinSearch(Name: String; var Location: Integer): Boolean;
var
First, Last, Mid: Integer;
Res: Integer;
begin
Result := False;
Location := 0;
if FCount > 0 then
begin
First := 0;
Last := FCount - 1;
while First <= Last do
begin
Mid := (First + Last) div 2;
Res := CompareText(Name,FArray[Mid].Name);
if Res > 0 then
First := Mid + 1
else
if Res < 0 then
Last := Mid - 1
else
begin
Location := Mid;
Result := True;
Exit;
end;
end;
Location := First;
end;
end;
function TFiles.GetItem(Index: Integer): TFile;
begin
if Index >= FCount then
raise EFileError.Create('Index out of range');
Result := FArray[Index];
end;
function TFiles.Insert(AFile: TFile): Integer;
begin
Result := -1;
if not Assigned(AFile) then Exit;
if not BinSearch(AFile.Name,Result) then
begin
InsertAt(AFile,Result);
MetadataChanged;
end;
end;
function TFiles.Insert(Name: String; ID: Byte; Kind: TFileKind): TFile;
var
Location: Integer;
begin
Result := nil;
if not BinSearch(Name,Location) then
begin
Result := TFile.Create(FContainer,Name,ID,Kind);
InsertAt(Result,Location);
end;
end;
procedure TFiles.InsertAt(AFile: TFile; Location: Integer);
var
X: Integer;
begin
inc(FCount);
if FCount > FSize then
begin
FSize := FSize + 8;
SetLength(FArray,FSize);
end;
for X := FCount - 2 downto Location do
FArray[X+1] := FArray[X];
FArray[Location] := AFile;
MetadataChanged;
end;
function TFiles.GetID: Byte;
var
X: Integer;
begin
for X := 1 to MAX_FILE_COUNT do
if Find(X) = -1 then
begin
Result := X;
Exit;
end;
raise EFileError.Create('File table is full');
end;
function TFiles.Remove(Name: String): Boolean;
var
Location: Integer;
begin
Result := BinSearch(Name,Location);
if Result then
begin
FArray[Location].Destroy;
//Delete(Location); { Called by Destroy }
end;
end;
function TFiles.Remove(AFile: TFile): Boolean;
var
Location: Integer;
begin
Result := Assigned(AFile);
if Result then
begin
Location := Find(AFile);
if Location > -1 then
begin
FArray[Location].Destroy;
//Delete(Location); { Called by Destroy }
end
else
Result := False;
end;
end;
function TFiles.Remove(AID: Byte): Boolean;
var
Location: Integer;
begin
Result := (AID > 0) and (AID <= MAX_FILE_COUNT);
if Result then
begin
Location := Find(AID);
if Location > -1 then
begin
FArray[Location].Destroy;
//Delete(Location); { Called by Destroy }
end;
end;
end;
procedure TFiles.Delete(AFile: TFile);
var
I: Integer;
begin
I := Find(AFile);
if I > -1 then
Delete(I);
end;
procedure TFiles.Delete(Location: Integer);
var
I: Integer;
begin
if (Location < 0) or (Location >= FCount) then
raise EFileError.Create('Index out of range');
for I := Location to FCount - 2 do
FArray[I] := FArray[I+1];
dec(FCount);
MetadataChanged;
end;
// Renames a virtual file. Throws an exception if OldName not found or if NewName already exists.
procedure TFiles.Rename(OldName, NewName: String);
var
I, Location: Integer;
F: TFile;
begin
if Find(NewName) <> nil then
raise EFileError.Create('A file named '+NewName+' already exists');
if BinSearch(OldName,Location) then
begin
F := FArray[Location];
for I := Location to FCount - 2 do
FArray[I] := FArray[I+1];
dec(FCount);
BinSearch(NewName,Location);
F.FName := NewName;
F.MetadataChanged;
InsertAt(F,Location);
MetadataChanged;
end
else
raise EFileError.Create('File '+OldName+' not found');
end;
function TFiles.PageNumChanged(OldPageNum, NewPageNum: Cardinal): Boolean;
var
I: Integer;
F: TFile;
begin
for I := 0 to FCount - 1 do
begin
F := FArray[I];
if Assigned(F) and F.PageNumChanged(OldPageNum,NewPageNum) then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
procedure TFiles.PageNumSwapped(PageNum1, PageNum2: TPageNum);
var
I: Integer;
F: TFile;
begin
for I := 0 to FCount - 1 do
begin
F := FArray[I];
if Assigned(F) then
F.PageNumSwapped(PageNum1,PageNum2);
end;
end;
procedure TFiles.Flush;
var
I: Integer;
begin