-
Notifications
You must be signed in to change notification settings - Fork 78
/
CompoundFile.cs
2888 lines (2319 loc) · 101 KB
/
CompoundFile.cs
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The Original Code is OpenMCDF - Compound Document Format library.
*
* The Initial Developer of the Original Code is Federico Blaseotto.*/
#define FLAT_WRITE // No optimization on the number of write operations
using System;
using System.Collections.Generic;
using System.IO;
using RedBlackTree;
namespace OpenMcdf
{
internal class CFItemComparer : IComparer<CFItem>
{
public int Compare(CFItem x, CFItem y)
{
// X CompareTo Y : X > Y --> 1 ; X < Y --> -1
return (x.DirEntry.CompareTo(y.DirEntry));
//Compare X < Y --> -1
}
}
/// <summary>
/// Configuration parameters for the compund files.
/// They can be OR-combined to configure
/// <see cref="T:OpenMcdf.CompoundFile">Compound file</see> behaviour.
/// All flags are NOT set by Default.
/// </summary>
[Flags]
public enum CFSConfiguration
{
/// <summary>
/// Sector Recycling turn off,
/// free sectors erasing off,
/// format validation exception raised
/// </summary>
Default = 1,
/// <summary>
/// Sector recycling reduces data writing performances
/// but avoids space wasting in scenarios with frequently
/// data manipulation of the same streams.
/// </summary>
SectorRecycle = 2,
/// <summary>
/// Free sectors are erased to avoid information leakage
/// </summary>
EraseFreeSectors = 4,
/// <summary>
/// No exception is raised when a validation error occurs.
/// This can possibly lead to a security issue but gives
/// a chance to corrupted files to load.
/// </summary>
NoValidationException = 8,
/// <summary>
/// If this flag is set true,
/// backing stream is kept open after CompoundFile disposal
/// </summary>
LeaveOpen = 16,
}
/// <summary>
/// Binary File Format Version. Sector size is 512 byte for version 3,
/// 4096 for version 4
/// </summary>
public enum CFSVersion : int
{
/// <summary>
/// Compound file version 3 - The default and most common version available. Sector size 512 bytes, 2GB max file size.
/// </summary>
Ver_3 = 3,
/// <summary>
/// Compound file version 4 - Sector size is 4096 bytes. Using this version could bring some compatibility problem with existing applications.
/// </summary>
Ver_4 = 4
}
/// <summary>
/// Update mode of the compound file.
/// Default is ReadOnly.
/// </summary>
public enum CFSUpdateMode
{
/// <summary>
/// ReadOnly update mode prevents overwriting
/// of the opened file.
/// Data changes are allowed but they have to be
/// persisted on a different file when required
/// using <see cref="M:OpenMcdf.CompoundFile.Save">method</see>
/// </summary>
ReadOnly,
/// <summary>
/// Update mode allows subsequent data changing operations
/// to be persisted directly on the opened file or stream
/// using the <see cref="M:OpenMcdf.CompoundFile.Commit">Commit</see>
/// method when required. Warning: this option may cause existing data loss if misused.
/// </summary>
Update
}
/// <summary>
/// Standard Microsoft© Compound File implementation.
/// It is also known as OLE/COM structured storage
/// and contains a hierarchy of storage and stream objects providing
/// efficent storage of multiple kinds of documents in a single file.
/// Version 3 and 4 of specifications are supported.
/// </summary>
public class CompoundFile : IDisposable
{
private CFSConfiguration configuration
= CFSConfiguration.Default;
/// <summary>
/// Get the configuration parameters of the CompoundFile object.
/// </summary>
public CFSConfiguration Configuration
{
get
{
return configuration;
}
}
/// <summary>
/// Returns the size of standard sectors switching on CFS version (3 or 4)
/// </summary>
/// <returns>Standard sector size</returns>
internal int GetSectorSize()
{
return 2 << (header.SectorShift - 1);
}
/// <summary>
/// Number of DIFAT entries in the header
/// </summary>
private const int HEADER_DIFAT_ENTRIES_COUNT = 109;
/// <summary>
/// Number of FAT entries in a DIFAT Sector
/// </summary>
private readonly int DIFAT_SECTOR_FAT_ENTRIES_COUNT = 127;
/// <summary>
/// Sectors ID entries in a FAT Sector
/// </summary>
private readonly int FAT_SECTOR_ENTRIES_COUNT = 128;
/// <summary>
/// Sector ID Size (int)
/// </summary>
private const int SIZE_OF_SID = 4;
/// <summary>
/// Flag for sector recycling.
/// </summary>
private bool sectorRecycle = false;
/// <summary>
/// Flag for unallocated sector zeroing out.
/// </summary>
private bool eraseFreeSectors = false;
/// <summary>
/// Initial capacity of the flushing queue used
/// to optimize commit writing operations
/// </summary>
private const int FLUSHING_QUEUE_SIZE = 6000;
/// <summary>
/// Maximum size of the flushing buffer used
/// to optimize commit writing operations
/// </summary>
private const int FLUSHING_BUFFER_MAX_SIZE = 1024 * 1024 * 16;
private SectorCollection sectors = new SectorCollection();
/// <summary>
/// CompoundFile header
/// </summary>
private Header header;
/// <summary>
/// Compound underlying stream. Null when new CF has been created.
/// </summary>
internal Stream sourceStream = null;
/// <summary>
/// Create a blank, version 3 compound file.
/// Sector recycle is turned off to achieve the best reading/writing
/// performance in most common scenarios.
/// </summary>
/// <example>
/// <code>
///
/// byte[] b = new byte[10000];
/// for (int i = 0; i < 10000; i++)
/// {
/// b[i % 120] = (byte)i;
/// }
///
/// CompoundFile cf = new CompoundFile();
/// CFStream myStream = cf.RootStorage.AddStream("MyStream");
///
/// Assert.IsNotNull(myStream);
/// myStream.SetData(b);
/// cf.Save("MyCompoundFile.cfs");
/// cf.Close();
///
/// </code>
/// </example>
public CompoundFile()
{
this.header = new Header();
this.sectorRecycle = false;
this.sectors.OnVer3SizeLimitReached += new Ver3SizeLimitReached(OnSizeLimitReached);
DIFAT_SECTOR_FAT_ENTRIES_COUNT = (GetSectorSize() / 4) - 1;
FAT_SECTOR_ENTRIES_COUNT = (GetSectorSize() / 4);
//Root --
IDirectoryEntry de = DirectoryEntry.New("Root Entry", StgType.StgRoot, directoryEntries);
rootStorage = new CFStorage(this, de);
rootStorage.DirEntry.StgType = StgType.StgRoot;
rootStorage.DirEntry.StgColor = StgColor.Black;
//this.InsertNewDirectoryEntry(rootStorage.DirEntry);
}
void OnSizeLimitReached()
{
Sector rangeLockSector = new Sector(GetSectorSize(), sourceStream);
sectors.Add(rangeLockSector);
rangeLockSector.Type = SectorType.RangeLockSector;
_transactionLockAdded = true;
_lockSectorId = rangeLockSector.Id;
}
/// <summary>
/// Create a new, blank, compound file.
/// </summary>
/// <param name="cfsVersion">Use a specific Compound File Version to set 512 or 4096 bytes sectors</param>
/// <param name="configFlags">Set <see cref="T:OpenMcdf.CFSConfiguration">configuration</see> parameters for the new compound file</param>
/// <example>
/// <code>
///
/// byte[] b = new byte[10000];
/// for (int i = 0; i < 10000; i++)
/// {
/// b[i % 120] = (byte)i;
/// }
///
/// CompoundFile cf = new CompoundFile(CFSVersion.Ver_4, CFSConfiguration.Default);
/// CFStream myStream = cf.RootStorage.AddStream("MyStream");
///
/// Assert.IsNotNull(myStream);
/// myStream.SetData(b);
/// cf.Save("MyCompoundFile.cfs");
/// cf.Close();
///
/// </code>
/// </example>
public CompoundFile(CFSVersion cfsVersion, CFSConfiguration configFlags)
{
this.configuration = configFlags;
bool sectorRecycle = configFlags.HasFlag(CFSConfiguration.SectorRecycle);
bool eraseFreeSectors = configFlags.HasFlag(CFSConfiguration.EraseFreeSectors);
this.header = new Header((ushort)cfsVersion);
this.sectorRecycle = sectorRecycle;
DIFAT_SECTOR_FAT_ENTRIES_COUNT = (GetSectorSize() / 4) - 1;
FAT_SECTOR_ENTRIES_COUNT = (GetSectorSize() / 4);
//Root --
IDirectoryEntry rootDir = DirectoryEntry.New("Root Entry", StgType.StgRoot, directoryEntries);
rootDir.StgColor = StgColor.Black;
//this.InsertNewDirectoryEntry(rootDir);
rootStorage = new CFStorage(this, rootDir);
//
}
/// <summary>
/// Load an existing compound file.
/// </summary>
/// <param name="fileName">Compound file to read from</param>
/// <example>
/// <code>
/// //A xls file should have a Workbook stream
/// String filename = "report.xls";
///
/// CompoundFile cf = new CompoundFile(filename);
/// CFStream foundStream = cf.RootStorage.GetStream("Workbook");
///
/// byte[] temp = foundStream.GetData();
///
/// Assert.IsNotNull(temp);
///
/// cf.Close();
/// </code>
/// </example>
/// <remarks>
/// File will be open in read-only mode: it has to be saved
/// with a different filename. A wrapping implementation has to be provided
/// in order to remove/substitute an existing file. Version will be
/// automatically recognized from the file. Sector recycle is turned off
/// to achieve the best reading/writing performance in most common scenarios.
/// </remarks>
public CompoundFile(String fileName)
{
this.sectorRecycle = false;
this.updateMode = CFSUpdateMode.ReadOnly;
this.eraseFreeSectors = false;
LoadFile(fileName);
DIFAT_SECTOR_FAT_ENTRIES_COUNT = (GetSectorSize() / 4) - 1;
FAT_SECTOR_ENTRIES_COUNT = (GetSectorSize() / 4);
}
/// <summary>
/// Load an existing compound file.
/// </summary>
/// <param name="fileName">Compound file to read from</param>
/// <param name="sectorRecycle">If true, recycle unused sectors</param>
/// <param name="updateMode">Select the update mode of the underlying data file</param>
/// <param name="eraseFreeSectors">If true, overwrite with zeros unallocated sectors</param>
/// <example>
/// <code>
/// String srcFilename = "data_YOU_CAN_CHANGE.xls";
///
/// CompoundFile cf = new CompoundFile(srcFilename, UpdateMode.Update, true, true);
///
/// Random r = new Random();
///
/// byte[] buffer = GetBuffer(r.Next(3, 4095), 0x0A);
///
/// cf.RootStorage.AddStream("MyStream").SetData(buffer);
///
/// //This will persist data to the underlying media.
/// cf.Commit();
/// cf.Close();
///
/// </code>
/// </example>
public CompoundFile(String fileName, CFSUpdateMode updateMode, CFSConfiguration configParameters)
{
this.configuration = configParameters;
this.validationExceptionEnabled = !configParameters.HasFlag(CFSConfiguration.NoValidationException);
this.sectorRecycle = configParameters.HasFlag(CFSConfiguration.SectorRecycle);
this.updateMode = updateMode;
this.eraseFreeSectors = configParameters.HasFlag(CFSConfiguration.EraseFreeSectors);
LoadFile(fileName);
DIFAT_SECTOR_FAT_ENTRIES_COUNT = (GetSectorSize() / 4) - 1;
FAT_SECTOR_ENTRIES_COUNT = (GetSectorSize() / 4);
}
private bool validationExceptionEnabled = true;
public bool ValidationExceptionEnabled
{
get { return validationExceptionEnabled; }
}
/// <summary>
/// Load an existing compound file.
/// </summary>
/// <param name="stream">A stream containing a compound file to read</param>
/// <param name="sectorRecycle">If true, recycle unused sectors</param>
/// <param name="updateMode">Select the update mode of the underlying data file</param>
/// <param name="eraseFreeSectors">If true, overwrite with zeros unallocated sectors</param>
/// <example>
/// <code>
///
/// String filename = "reportREAD.xls";
///
/// FileStream fs = new FileStream(filename, FileMode.Open);
/// CompoundFile cf = new CompoundFile(fs, UpdateMode.ReadOnly, false, false);
/// CFStream foundStream = cf.RootStorage.GetStream("Workbook");
///
/// byte[] temp = foundStream.GetData();
///
/// Assert.IsNotNull(temp);
///
/// cf.Close();
///
/// </code>
/// </example>
/// <exception cref="T:OpenMcdf.CFException">Raised when trying to open a non-seekable stream</exception>
/// <exception cref="T:OpenMcdf.CFException">Raised stream is null</exception>
public CompoundFile(Stream stream, CFSUpdateMode updateMode, CFSConfiguration configParameters)
{
this.configuration = configParameters;
this.validationExceptionEnabled = !configParameters.HasFlag(CFSConfiguration.NoValidationException);
this.sectorRecycle = configParameters.HasFlag(CFSConfiguration.SectorRecycle);
this.eraseFreeSectors = configParameters.HasFlag(CFSConfiguration.EraseFreeSectors);
this.closeStream = !configParameters.HasFlag(CFSConfiguration.LeaveOpen);
this.updateMode = updateMode;
LoadStream(stream);
DIFAT_SECTOR_FAT_ENTRIES_COUNT = (GetSectorSize() / 4) - 1;
FAT_SECTOR_ENTRIES_COUNT = (GetSectorSize() / 4);
}
/// <summary>
/// Load an existing compound file from a stream.
/// </summary>
/// <param name="stream">Streamed compound file</param>
/// <example>
/// <code>
///
/// String filename = "reportREAD.xls";
///
/// FileStream fs = new FileStream(filename, FileMode.Open);
/// CompoundFile cf = new CompoundFile(fs);
/// CFStream foundStream = cf.RootStorage.GetStream("Workbook");
///
/// byte[] temp = foundStream.GetData();
///
/// Assert.IsNotNull(temp);
///
/// cf.Close();
///
/// </code>
/// </example>
/// <exception cref="T:OpenMcdf.CFException">Raised when trying to open a non-seekable stream</exception>
/// <exception cref="T:OpenMcdf.CFException">Raised stream is null</exception>
public CompoundFile(Stream stream)
{
LoadStream(stream);
DIFAT_SECTOR_FAT_ENTRIES_COUNT = (GetSectorSize() / 4) - 1;
FAT_SECTOR_ENTRIES_COUNT = (GetSectorSize() / 4);
}
private CFSUpdateMode updateMode = CFSUpdateMode.ReadOnly;
private String fileName = String.Empty;
/// <summary>
/// Commit data changes since the previously commit operation
/// to the underlying supporting stream or file on the disk.
/// </summary>
/// <remarks>
/// This method can be used
/// only if the supporting stream has been opened in
/// <see cref="T:OpenMcdf.UpdateMode">Update mode</see>.
/// </remarks>
public void Commit()
{
Commit(false);
}
#if !FLAT_WRITE
private byte[] buffer = new byte[FLUSHING_BUFFER_MAX_SIZE];
private Queue<Sector> flushingQueue = new Queue<Sector>(FLUSHING_QUEUE_SIZE);
#endif
/// <summary>
/// Commit data changes since the previously commit operation
/// to the underlying supporting stream or file on the disk.
/// </summary>
/// <param name="releaseMemory">If true, release loaded sectors to limit memory usage but reduces following read operations performance</param>
/// <remarks>
/// This method can be used only if
/// the supporting stream has been opened in
/// <see cref="T:OpenMcdf.UpdateMode">Update mode</see>.
/// </remarks>
public void Commit(bool releaseMemory)
{
if (_disposed)
throw new CFDisposedException("Compound File closed: cannot commit data");
if (updateMode != CFSUpdateMode.Update)
throw new CFInvalidOperation("Cannot commit data in Read-Only update mode");
//try
//{
#if !FLAT_WRITE
int sId = -1;
int sCount = 0;
int bufOffset = 0;
#endif
int sSize = GetSectorSize();
if (header.MajorVersion != (ushort)CFSVersion.Ver_3)
CheckForLockSector();
sourceStream.Seek(0, SeekOrigin.Begin);
sourceStream.Write((byte[])Array.CreateInstance(typeof(byte), GetSectorSize()), 0, sSize);
CommitDirectory();
bool gap = true;
for (int i = 0; i < sectors.Count; i++)
{
#if FLAT_WRITE
//Note:
//Here sectors should not be loaded dynamically because
//if they are null it means that no change has involved them;
Sector s = (Sector)sectors[i];
if (s != null && s.DirtyFlag)
{
if (gap)
sourceStream.Seek((long)((long)(sSize) + (long)i * (long)sSize), SeekOrigin.Begin);
sourceStream.Write(s.GetData(), 0, sSize);
sourceStream.Flush();
s.DirtyFlag = false;
gap = false;
}
else
{
gap = true;
}
if (s != null && releaseMemory)
{
s.ReleaseData();
s = null;
sectors[i] = null;
}
#else
Sector s = sectors[i] as Sector;
if (s != null && s.DirtyFlag && flushingQueue.Count < (int)(buffer.Length / sSize))
{
//First of a block of contiguous sectors, mark id, start enqueuing
if (gap)
{
sId = s.Id;
gap = false;
}
flushingQueue.Enqueue(s);
}
else
{
//Found a gap, stop enqueuing, flush a write operation
gap = true;
sCount = flushingQueue.Count;
if (sCount == 0) continue;
bufOffset = 0;
while (flushingQueue.Count > 0)
{
Sector r = flushingQueue.Dequeue();
Buffer.BlockCopy(r.GetData(), 0, buffer, bufOffset, sSize);
r.DirtyFlag = false;
if (releaseMemory)
{
r.ReleaseData();
}
bufOffset += sSize;
}
sourceStream.Seek(((long)sSize + (long)sId * (long)sSize), SeekOrigin.Begin);
sourceStream.Write(buffer, 0, sCount * sSize);
//Console.WriteLine("W - " + (int)(sCount * sSize ));
}
#endif
}
#if !FLAT_WRITE
sCount = flushingQueue.Count;
bufOffset = 0;
while (flushingQueue.Count > 0)
{
Sector r = flushingQueue.Dequeue();
Buffer.BlockCopy(r.GetData(), 0, buffer, bufOffset, sSize);
r.DirtyFlag = false;
if (releaseMemory)
{
r.ReleaseData();
r = null;
}
bufOffset += sSize;
}
if (sCount != 0)
{
sourceStream.Seek((long)sSize + (long)sId * (long)sSize, SeekOrigin.Begin);
sourceStream.Write(buffer, 0, sCount * sSize);
//Console.WriteLine("W - " + (int)(sCount * sSize));
}
#endif
// Seek to beginning position and save header (first 512 or 4096 bytes)
sourceStream.Seek(0, SeekOrigin.Begin);
header.Write(sourceStream);
sourceStream.SetLength((long)(sectors.Count + 1) * sSize);
sourceStream.Flush();
if (releaseMemory)
GC.Collect();
//}
//catch (Exception ex)
//{
// throw new CFException("Internal error while committing data", ex);
//}
}
/// <summary>
/// Load compound file from an existing stream.
/// </summary>
/// <param name="stream">Stream to load compound file from</param>
private void Load(Stream stream)
{
try
{
this.header = new Header();
this.directoryEntries = new List<IDirectoryEntry>();
this.sourceStream = stream;
header.Read(stream);
int n_sector = Ceiling(((double)(stream.Length - GetSectorSize()) / (double)GetSectorSize()));
if (stream.Length > 0x7FFFFF0)
this._transactionLockAllocated = true;
sectors = new SectorCollection();
//sectors = new ArrayList();
for (int i = 0; i < n_sector; i++)
{
sectors.Add(null);
}
LoadDirectories();
this.rootStorage
= new CFStorage(this, directoryEntries[0]);
}
catch (Exception)
{
if (stream != null && closeStream)
stream.Close();
throw;
}
}
private void LoadFile(String fileName)
{
this.fileName = fileName;
FileStream fs = null;
try
{
if (this.updateMode == CFSUpdateMode.ReadOnly)
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
else
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
}
Load(fs);
}
catch
{
if (fs != null)
fs.Close();
throw;
}
}
private void LoadStream(Stream stream)
{
if (stream == null)
throw new CFException("Stream parameter cannot be null");
if (!stream.CanSeek)
throw new CFException("Cannot load a non-seekable Stream");
stream.Seek(0, SeekOrigin.Begin);
Load(stream);
}
/// <summary>
/// Return true if this compound file has been
/// loaded from an existing file or stream
/// </summary>
public bool HasSourceStream
{
get { return sourceStream != null; }
}
private void PersistMiniStreamToStream(List<Sector> miniSectorChain)
{
List<Sector> miniStream
= GetSectorChain(RootEntry.StartSetc, SectorType.Normal);
StreamView miniStreamView
= new StreamView(
miniStream,
GetSectorSize(),
this.rootStorage.Size,
null,
sourceStream);
for (int i = 0; i < miniSectorChain.Count; i++)
{
Sector s = miniSectorChain[i];
if (s.Id == -1)
throw new CFException("Invalid minisector index");
// Ministream sectors already allocated
miniStreamView.Seek(Sector.MINISECTOR_SIZE * s.Id, SeekOrigin.Begin);
miniStreamView.Write(s.GetData(), 0, Sector.MINISECTOR_SIZE);
}
}
/// <summary>
/// Allocate space, setup sectors id and refresh header
/// for the new or updated mini sector chain.
/// </summary>
/// <param name="sectorChain">The new MINI sector chain</param>
private void AllocateMiniSectorChain(List<Sector> sectorChain)
{
List<Sector> miniFAT
= GetSectorChain(header.FirstMiniFATSectorID, SectorType.Normal);
List<Sector> miniStream
= GetSectorChain(RootEntry.StartSetc, SectorType.Normal);
StreamView miniFATView
= new StreamView(
miniFAT,
GetSectorSize(),
header.MiniFATSectorsNumber * Sector.MINISECTOR_SIZE,
null,
this.sourceStream,
true
);
StreamView miniStreamView
= new StreamView(
miniStream,
GetSectorSize(),
this.rootStorage.Size,
null,
sourceStream);
// Set updated/new sectors within the ministream
// We are writing data in a NORMAL Sector chain.
for (int i = 0; i < sectorChain.Count; i++)
{
Sector s = sectorChain[i];
if (s.Id == -1)
{
// Allocate, position ministream at the end of already allocated
// ministream's sectors
miniStreamView.Seek(this.rootStorage.Size + Sector.MINISECTOR_SIZE, SeekOrigin.Begin);
//miniStreamView.Write(s.GetData(), 0, Sector.MINISECTOR_SIZE);
s.Id = (int)(miniStreamView.Position - Sector.MINISECTOR_SIZE) / Sector.MINISECTOR_SIZE;
this.rootStorage.DirEntry.Size = miniStreamView.Length;
}
}
// Update miniFAT
for (int i = 0; i < sectorChain.Count - 1; i++)
{
Int32 currentId = sectorChain[i].Id;
Int32 nextId = sectorChain[i + 1].Id;
miniFATView.Seek(currentId * 4, SeekOrigin.Begin);
miniFATView.Write(BitConverter.GetBytes(nextId), 0, 4);
}
// Write End of Chain in MiniFAT
miniFATView.Seek(sectorChain[sectorChain.Count - 1].Id * SIZE_OF_SID, SeekOrigin.Begin);
miniFATView.Write(BitConverter.GetBytes(Sector.ENDOFCHAIN), 0, 4);
// Update sector chains
AllocateSectorChain(miniStreamView.BaseSectorChain);
AllocateSectorChain(miniFATView.BaseSectorChain);
//Update HEADER and root storage when ministream changes
if (miniFAT.Count > 0)
{
this.rootStorage.DirEntry.StartSetc = miniStream[0].Id;
header.MiniFATSectorsNumber = (uint)miniFAT.Count;
header.FirstMiniFATSectorID = miniFAT[0].Id;
}
}
internal void FreeData(CFStream stream)
{
if (stream.Size == 0)
return;
List<Sector> sectorChain = null;
if (stream.Size < header.MinSizeStandardStream)
{
sectorChain = GetSectorChain(stream.DirEntry.StartSetc, SectorType.Mini);
FreeMiniChain(sectorChain, this.eraseFreeSectors);
}
else
{
sectorChain = GetSectorChain(stream.DirEntry.StartSetc, SectorType.Normal);
FreeChain(sectorChain, this.eraseFreeSectors);
}
stream.DirEntry.StartSetc = Sector.ENDOFCHAIN;
stream.DirEntry.Size = 0;
}
private void FreeChain(List<Sector> sectorChain, bool zeroSector)
{
FreeChain(sectorChain, 0, zeroSector);
}
private void FreeChain(List<Sector> sectorChain, int nth_sector_to_remove, bool zeroSector)
{
// Dummy zero buffer
byte[] ZEROED_SECTOR = new byte[GetSectorSize()];
List<Sector> FAT
= GetSectorChain(-1, SectorType.FAT);
StreamView FATView
= new StreamView(FAT, GetSectorSize(), FAT.Count * GetSectorSize(), null, sourceStream);
// Zeroes out sector data (if required)-------------
if (zeroSector)
{
for (int i = nth_sector_to_remove; i < sectorChain.Count; i++)
{
Sector s = sectorChain[i];
s.ZeroData();
}
}
// Update FAT marking unallocated sectors ----------
for (int i = nth_sector_to_remove; i < sectorChain.Count; i++)
{
Int32 currentId = sectorChain[i].Id;
FATView.Seek(currentId * 4, SeekOrigin.Begin);
FATView.Write(BitConverter.GetBytes(Sector.FREESECT), 0, 4);
}
// Write new end of chain if partial free ----------
if (nth_sector_to_remove > 0 && sectorChain.Count > 0)
{
FATView.Seek(sectorChain[nth_sector_to_remove - 1].Id * 4, SeekOrigin.Begin);
FATView.Write(BitConverter.GetBytes(Sector.ENDOFCHAIN), 0, 4);
}
}
private void FreeMiniChain(List<Sector> sectorChain, bool zeroSector)
{
FreeMiniChain(sectorChain, 0, zeroSector);
}
private void FreeMiniChain(List<Sector> sectorChain, int nth_sector_to_remove, bool zeroSector)
{
byte[] ZEROED_MINI_SECTOR = new byte[Sector.MINISECTOR_SIZE];
List<Sector> miniFAT
= GetSectorChain(header.FirstMiniFATSectorID, SectorType.Normal);
List<Sector> miniStream
= GetSectorChain(RootEntry.StartSetc, SectorType.Normal);
StreamView miniFATView
= new StreamView(miniFAT, GetSectorSize(), header.MiniFATSectorsNumber * Sector.MINISECTOR_SIZE, null, sourceStream);
StreamView miniStreamView
= new StreamView(miniStream, GetSectorSize(), this.rootStorage.Size, null, sourceStream);
// Set updated/new sectors within the ministream ----------
if (zeroSector)
{
for (int i = nth_sector_to_remove; i < sectorChain.Count; i++)
{
Sector s = sectorChain[i];
if (s.Id != -1)
{
// Overwrite
miniStreamView.Seek(Sector.MINISECTOR_SIZE * s.Id, SeekOrigin.Begin);
miniStreamView.Write(ZEROED_MINI_SECTOR, 0, Sector.MINISECTOR_SIZE);
}
}
}
// Update miniFAT ---------------------------------------
for (int i = nth_sector_to_remove; i < sectorChain.Count; i++)
{
Int32 currentId = sectorChain[i].Id;
miniFATView.Seek(currentId * 4, SeekOrigin.Begin);
miniFATView.Write(BitConverter.GetBytes(Sector.FREESECT), 0, 4);
}
// Write End of Chain in MiniFAT ---------------------------------------
//miniFATView.Seek(sectorChain[(sectorChain.Count - 1) - nth_sector_to_remove].Id * SIZE_OF_SID, SeekOrigin.Begin);
//miniFATView.Write(BitConverter.GetBytes(Sector.ENDOFCHAIN), 0, 4);
// Write End of Chain in MiniFAT ---------------------------------------
if (nth_sector_to_remove > 0 && sectorChain.Count > 0)
{
miniFATView.Seek(sectorChain[nth_sector_to_remove - 1].Id * 4, SeekOrigin.Begin);
miniFATView.Write(BitConverter.GetBytes(Sector.ENDOFCHAIN), 0, 4);
}
// Update sector chains ---------------------------------------
AllocateSectorChain(miniStreamView.BaseSectorChain);
AllocateSectorChain(miniFATView.BaseSectorChain);
//Update HEADER and root storage when ministream changes
if (miniFAT.Count > 0)
{
this.rootStorage.DirEntry.StartSetc = miniStream[0].Id;
header.MiniFATSectorsNumber = (uint)miniFAT.Count;
header.FirstMiniFATSectorID = miniFAT[0].Id;
}
}