Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
2915 lines (2618 loc) · 115 KB
/
Copy pathProgram.cs
File metadata and controls
2915 lines (2618 loc) · 115 KB
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
// ============================================================================
// Xbox 360 USB Explorer — Complete Rewrite
// Single-file Program.cs
// Target: .NET Framework 4.0 – 4.8
// Namespace: Xbox360_USB_Explorer
// No external libraries. No Resources. No App.config.
// FATX reference: https://free60.org/System-Software/Systems/FATX/
// https://github.com/aerosoul94/FATXTools
// ============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32.SafeHandles;
/*
[assembly: AssemblyTitle("Xbox 360 USB Explorer")]
[assembly: AssemblyDescription("FATX/XTAF file-system explorer for Xbox 360 USB drives and HDD images.")]
[assembly: AssemblyCompany("Xbox360_USB_Explorer")]
[assembly: AssemblyProduct("Xbox 360 USB Explorer")]
[assembly: AssemblyCopyright("Rewritten 2026 – original by Slasher / Darkjump")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: Guid("b1a2c3d4-e5f6-7890-abcd-ef1234567890")]
[assembly: ComVisible(false)]
*/
namespace Xbox360_USB_Explorer
{
// ========================================================================
// 1. LOGGING (Trace → Console + File, coloured, datetime-stamped)
// ========================================================================
internal static class Log
{
private static readonly object _lock = new object();
private static TextWriterTraceListener _fileListener;
public static void Init()
{
Trace.AutoFlush = true;
// Console listener (coloured output handled by ColoredConsoleListener)
Trace.Listeners.Add(new ColoredConsoleListener());
// File listener – logs\<yyyy-MM-dd_HH-mm-ss>.log
try
{
string logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
if (!Directory.Exists(logDir)) Directory.CreateDirectory(logDir);
string logFile = Path.Combine(logDir,
DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + ".log");
_fileListener = new TextWriterTraceListener(logFile, "FileLog");
Trace.Listeners.Add(_fileListener);
Info("Log file: " + logFile);
}
catch (Exception ex)
{
Trace.Listeners.Add(new ColoredConsoleListener());
Warn("Cannot create log file: " + ex.Message);
}
}
public static void Shutdown()
{
try { Trace.Flush(); } catch { }
}
public static void Info(string msg) { Write("INFO", msg, ConsoleColor.Cyan); }
public static void Ok(string msg) { Write("OK", msg, ConsoleColor.Green); }
public static void Warn(string msg) { Write("WARN", msg, ConsoleColor.Yellow); }
public static void Error(string msg) { Write("ERROR", msg, ConsoleColor.Red); }
public static void Debug(string msg) { Write("DEBUG", msg, ConsoleColor.Magenta); }
public static void Status(string msg) { Write("STAT", msg, ConsoleColor.White); }
private static void Write(string level, string msg, ConsoleColor color)
{
string line = string.Format("[{0}] [{1}] {2}",
DateTime.Now.ToString("HH:mm:ss.fff"), level, msg);
lock (_lock)
{
ConsoleColor old = Console.ForegroundColor;
Console.ForegroundColor = color;
Trace.WriteLine(line);
Console.ForegroundColor = old;
}
}
}
/// <summary>TraceListener that writes to Console (avoids double writes).</summary>
internal sealed class ColoredConsoleListener : TraceListener
{
public override void Write(string message) { Console.Write(message); }
public override void WriteLine(string message) { Console.WriteLine(message); }
}
// ========================================================================
// 2. WIN32 NATIVE (raw disk, admin check, elevation)
// ========================================================================
internal static class Win32Native
{
[StructLayout(LayoutKind.Sequential)]
internal struct DISK_GEOMETRY
{
public long Cylinders;
public uint MediaType;
public uint TracksPerCylinder;
public uint SectorsPerTrack;
public uint BytesPerSector;
public long DiskSize
{
get { return Cylinders * TracksPerCylinder * SectorsPerTrack * BytesPerSector; }
}
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern SafeFileHandle CreateFile(
string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode,
IntPtr lpSecurityAttributes, FileMode dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeviceIoControl(
SafeHandle hDevice, uint dwIoControlCode,
IntPtr lpInBuffer, uint nInBufferSize,
ref DISK_GEOMETRY lpOutBuffer, uint nOutBufferSize,
out uint lpBytesReturned, IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr hObject);
internal const uint IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000;
internal const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
internal const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
internal const uint FILE_ATTRIBUTE_DEVICE = 0x00000040;
internal static bool IsAdministrator()
{
try
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(id);
return p.IsInRole(WindowsBuiltInRole.Administrator);
}
catch { return false; }
}
/// <summary>Re-launch current exe elevated (UAC).</summary>
internal static void ElevateAndRestart(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = Assembly.GetExecutingAssembly().Location;
psi.Verb = "runas";
psi.UseShellExecute = true;
if (args != null && args.Length > 0)
psi.Arguments = string.Join(" ", args);
try { Process.Start(psi); }
catch (Win32Exception) { /* user cancelled UAC */ }
Environment.Exit(0);
}
}
// ========================================================================
// 3. FATX CONSTANTS
// ========================================================================
internal static class FatxConst
{
public const uint MAGIC = 0x58544146; // "XTAF" big-endian
public const int SECTOR_SIZE = 0x200; // 512
public const int HEADER_SIZE = 0x1000; // 4096
public const int DIRENT_SIZE = 0x40; // 64
public const int MAX_FILENAME = 42;
public const uint FAT16_THRESHOLD = 0xFFF0; // 65520
public const uint CLUSTER_LAST = 0xFFFFFFFF;
public const ushort CLUSTER_LAST16 = 0xFFFF;
public const uint CLUSTER_FREE = 0;
public const byte DIRENT_NEVER_USED = 0x00;
public const byte DIRENT_NEVER_USED2 = 0xFF;
public const byte DIRENT_DELETED = 0xE5;
// File attributes
public const byte ATTR_READONLY = 0x01;
public const byte ATTR_HIDDEN = 0x02;
public const byte ATTR_SYSTEM = 0x04;
public const byte ATTR_DIRECTORY = 0x10;
public const byte ATTR_ARCHIVE = 0x20;
// USB drive layout
public const long USB_CACHE_OFFSET = 0x8000400; // 134218752
public const long USB_CACHE_SIZE = 0x12000400;
public const long USB_DATA_OFFSET = 0x20000000; // 536870912
// HDD layout (retail)
public const long HDD_CACHE_OFFSET = 0x80080000; // 2148007936
public const long HDD_CACHE_SIZE = 0xA0E30000;
public const long HDD_COMPAT_OFFSET = 0x120EB0000; // 4847239168
public const long HDD_COMPAT_SIZE = 0x10000000;
public const long HDD_DATA_OFFSET = 0x130EB0000; // 5115674624
// Read buffer for large files
public const int IO_BUFFER_SIZE = 1024 * 1024; // 1 MB
}
// ========================================================================
// 4. ENDIAN HELPERS (FATX is big-endian)
// ========================================================================
internal static class Endian
{
public static ushort ReadU16BE(byte[] buf, int off)
{
return (ushort)((buf[off] << 8) | buf[off + 1]);
}
public static uint ReadU32BE(byte[] buf, int off)
{
return (uint)((buf[off] << 24) | (buf[off + 1] << 16) |
(buf[off + 2] << 8) | buf[off + 3]);
}
public static ulong ReadU64BE(byte[] buf, int off)
{
return ((ulong)ReadU32BE(buf, off) << 32) | ReadU32BE(buf, off + 4);
}
public static void WriteU16BE(byte[] buf, int off, ushort v)
{
buf[off] = (byte)(v >> 8);
buf[off + 1] = (byte)(v);
}
public static void WriteU32BE(byte[] buf, int off, uint v)
{
buf[off] = (byte)(v >> 24);
buf[off + 1] = (byte)(v >> 16);
buf[off + 2] = (byte)(v >> 8);
buf[off + 3] = (byte)(v);
}
}
// ========================================================================
// 5. PARTITION STREAM (abstraction over file / multi-file / raw disk)
// ========================================================================
internal sealed class PartitionStream : IDisposable
{
private Stream[] _streams;
private long[] _lengths;
private long _totalLength;
private long _globalOffset;
private long _lengthOverride;
private int _curIdx;
private bool _disposed;
public long GlobalOffset
{
get { return _globalOffset; }
set { _globalOffset = value; }
}
public long LengthOverride
{
get { return _lengthOverride; }
set { _lengthOverride = value; }
}
public long TotalLength
{
get { return _lengthOverride > 0 ? _lengthOverride : _totalLength; }
}
// Single file
public PartitionStream(string path)
{
_streams = new Stream[] { new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) };
InitLengths();
}
// Multiple files (USB Data0001, Data0002, …)
public PartitionStream(string[] paths)
{
_streams = new Stream[paths.Length];
for (int i = 0; i < paths.Length; i++)
_streams[i] = new FileStream(paths[i], FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
InitLengths();
}
// Existing stream (raw disk)
public PartitionStream(Stream s)
{
_streams = new Stream[] { s };
InitLengths();
}
private void InitLengths()
{
_lengths = new long[_streams.Length];
_totalLength = 0;
for (int i = 0; i < _streams.Length; i++)
{
_lengths[i] = _streams[i].Length;
_totalLength += _lengths[i];
}
_curIdx = 0;
}
/// <summary>Seek to absolute offset (relative to partition start + GlobalOffset).</summary>
public void SeekTo(long offset)
{
long absolute = offset + _globalOffset;
long limit = TotalLength;
if (absolute < 0)
throw new IOException(string.Format(
"Seek before start: offset={0}, global=0x{1:X} → absolute=0x{2:X}",
offset, _globalOffset, absolute));
// Мягкая проверка: позволяем читать до конца диска,
// но логируем выход за ожидаемый размер раздела
if (absolute > limit)
{
Log.Debug(string.Format(
"Seek beyond partition: absolute=0x{0:X}, limit=0x{1:X} (Δ={2})",
absolute, limit, absolute - limit));
// Не бросаем исключение — даём прочитать,
// а FATX-движок сам обработает мусор
}
if (_streams.Length == 1)
{
_streams[0].Position = absolute;
_curIdx = 0;
return;
}
long rem = absolute;
for (int i = 0; i < _streams.Length; i++)
{
if (rem < _lengths[i])
{
_curIdx = i;
_streams[i].Position = rem;
return;
}
rem -= _lengths[i];
}
_curIdx = _streams.Length - 1;
_streams[_curIdx].Position = _lengths[_curIdx];
}
public int Read(byte[] buf, int off, int count)
{
if (_streams.Length == 1)
return _streams[0].Read(buf, off, count);
int total = 0;
while (count > 0 && _curIdx < _streams.Length)
{
int n = _streams[_curIdx].Read(buf, off + total, count);
if (n == 0)
{
_curIdx++;
if (_curIdx < _streams.Length) _streams[_curIdx].Position = 0;
continue;
}
total += n;
count -= n;
}
return total;
}
public void Write(byte[] buf, int off, int count)
{
if (_streams.Length == 1)
{
_streams[0].Write(buf, off, count);
return;
}
while (count > 0 && _curIdx < _streams.Length)
{
long remaining = _lengths[_curIdx] - _streams[_curIdx].Position;
int chunk = (int)Math.Min(count, remaining);
if (chunk <= 0)
{
_curIdx++;
if (_curIdx < _streams.Length) _streams[_curIdx].Position = 0;
continue;
}
_streams[_curIdx].Write(buf, off, chunk);
off += chunk;
count -= chunk;
}
}
public byte[] ReadBytes(int count)
{
byte[] buf = new byte[count];
int read = Read(buf, 0, count);
if (read < count)
Array.Resize(ref buf, read);
return buf;
}
public void WriteBytes(byte[] data)
{
Write(data, 0, data.Length);
}
public void Flush()
{
for (int i = 0; i < _streams.Length; i++)
_streams[i].Flush();
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
for (int i = 0; i < _streams.Length; i++)
{
try { _streams[i].Dispose(); } catch { }
}
}
}
// ========================================================================
// 6. RAW DISK STREAM (Win32 physical drive)
// ========================================================================
internal sealed class RawDiskStream : Stream
{
private SafeFileHandle _handle;
private FileStream _fs;
private long _diskSize;
private long _pos;
private byte[] _sectorBuf = new byte[FatxConst.SECTOR_SIZE];
private long _cachedSector = -1;
private bool _dirty;
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return true; } }
public override bool CanSeek { get { return true; } }
public override long Length { get { return _diskSize; } }
public override long Position
{
get { return _pos; }
set { _pos = value; }
}
public RawDiskStream(int driveIndex)
{
string path = @"\\.\PhysicalDrive" + driveIndex;
_handle = Win32Native.CreateFile(path,
FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero,
FileMode.Open,
Win32Native.FILE_FLAG_NO_BUFFERING |
Win32Native.FILE_FLAG_WRITE_THROUGH |
Win32Native.FILE_ATTRIBUTE_DEVICE,
IntPtr.Zero);
if (_handle.IsInvalid)
throw new IOException("Cannot open " + path +
" (error " + Marshal.GetLastWin32Error() + "). Run as Administrator.");
Win32Native.DISK_GEOMETRY geo = new Win32Native.DISK_GEOMETRY();
uint ret;
bool geoOk = Win32Native.DeviceIoControl(_handle,
Win32Native.IOCTL_DISK_GET_DRIVE_GEOMETRY,
IntPtr.Zero, 0, ref geo,
(uint)Marshal.SizeOf(typeof(Win32Native.DISK_GEOMETRY)),
out ret, IntPtr.Zero);
if (geoOk && geo.DiskSize > 0)
{
_diskSize = geo.DiskSize;
}
else
{
// Fallback: IOCTL_DISK_GET_LENGTH_INFO (0x0007405C)
long len = 0;
uint ret2;
bool lenOk = DeviceIoControl_GetLength(_handle, out len, out ret2);
if (lenOk && len > 0)
{
_diskSize = len;
Log.Info("Disk size via GET_LENGTH_INFO: " + len);
}
else
{
_diskSize = 0;
Log.Warn("Cannot determine disk size for " + path);
}
}
_fs = new FileStream(_handle, FileAccess.ReadWrite, FatxConst.SECTOR_SIZE);
_pos = 0;
}
// Дополнительный P/Invoke для fallback
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeviceIoControl(
SafeHandle hDevice, uint dwIoControlCode,
IntPtr lpInBuffer, uint nInBufferSize,
out long lpOutBuffer, uint nOutBufferSize,
out uint lpBytesReturned, IntPtr lpOverlapped);
private static bool DeviceIoControl_GetLength(SafeHandle h, out long length, out uint ret)
{
const uint IOCTL_DISK_GET_LENGTH_INFO = 0x0007405C;
return DeviceIoControl(h, IOCTL_DISK_GET_LENGTH_INFO,
IntPtr.Zero, 0, out length, 8, out ret, IntPtr.Zero);
}
private void FlushSector()
{
if (_dirty && _cachedSector >= 0)
{
_fs.Position = _cachedSector * FatxConst.SECTOR_SIZE;
_fs.Write(_sectorBuf, 0, FatxConst.SECTOR_SIZE);
_fs.Flush();
_dirty = false;
}
}
private void LoadSector(long sector)
{
if (sector == _cachedSector) return;
FlushSector();
_cachedSector = sector;
_fs.Position = sector * FatxConst.SECTOR_SIZE;
int r = _fs.Read(_sectorBuf, 0, FatxConst.SECTOR_SIZE);
if (r < FatxConst.SECTOR_SIZE)
Array.Clear(_sectorBuf, r, FatxConst.SECTOR_SIZE - r);
}
public override int Read(byte[] buffer, int offset, int count)
{
int done = 0;
while (done < count)
{
long sector = _pos / FatxConst.SECTOR_SIZE;
int inSector = (int)(_pos % FatxConst.SECTOR_SIZE);
LoadSector(sector);
int chunk = Math.Min(count - done, FatxConst.SECTOR_SIZE - inSector);
Array.Copy(_sectorBuf, inSector, buffer, offset + done, chunk);
_pos += chunk;
done += chunk;
}
return done;
}
public override void Write(byte[] buffer, int offset, int count)
{
int done = 0;
while (done < count)
{
long sector = _pos / FatxConst.SECTOR_SIZE;
int inSector = (int)(_pos % FatxConst.SECTOR_SIZE);
LoadSector(sector);
int chunk = Math.Min(count - done, FatxConst.SECTOR_SIZE - inSector);
Array.Copy(buffer, offset + done, _sectorBuf, inSector, chunk);
_dirty = true;
_pos += chunk;
done += chunk;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Begin) _pos = offset;
else if (origin == SeekOrigin.Current) _pos += offset;
else _pos = _diskSize + offset;
return _pos;
}
public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Flush() { FlushSector(); _fs.Flush(); }
protected override void Dispose(bool disposing)
{
if (disposing)
{
FlushSector();
if (_fs != null) _fs.Dispose();
}
base.Dispose(disposing);
}
}
// ========================================================================
// 7. FATX FILE-SYSTEM ENGINE
// ========================================================================
/// <summary>Parsed FATX header.</summary>
internal sealed class FatxHeader
{
public uint Magic;
public uint VolumeId;
public uint SectorsPerCluster;
public uint RootCluster;
public uint ClusterSize; // derived
public bool IsFat32; // derived
public int FatEntrySize; // 2 or 4
public long FatOffset; // = HEADER_SIZE
public long FatSize; // aligned to page
public long FileAreaOffset;
public uint MaxClusters;
public static FatxHeader Read(PartitionStream io, long partitionLength)
{
// БЫЛО: io.GlobalOffset = 0; // ← ломает offset для HDD
// СТАЛО: не трогаем GlobalOffset — он уже выставлен в FatxPartition
io.SeekTo(0); // SeekTo сам прибавит GlobalOffset → попадём на HDD_DATA_OFFSET
byte[] hdr = io.ReadBytes(FatxConst.HEADER_SIZE);
FatxHeader h = new FatxHeader();
h.Magic = Endian.ReadU32BE(hdr, 0);
h.VolumeId = Endian.ReadU32BE(hdr, 4);
h.SectorsPerCluster = Endian.ReadU32BE(hdr, 8);
h.RootCluster = Endian.ReadU32BE(hdr, 12);
if (h.Magic != FatxConst.MAGIC)
throw new InvalidDataException(
string.Format("Bad FATX magic: 0x{0:X8} (expected 0x{1:X8}). " +
"GlobalOffset=0x{2:X}, partitionLen=0x{3:X}",
h.Magic, FatxConst.MAGIC,
io.GlobalOffset, partitionLength));
h.ClusterSize = h.SectorsPerCluster * FatxConst.SECTOR_SIZE;
if (h.ClusterSize == 0) h.ClusterSize = 0x4000;
h.MaxClusters = (uint)(partitionLength / h.ClusterSize) + 1;
h.IsFat32 = h.MaxClusters >= FatxConst.FAT16_THRESHOLD;
h.FatEntrySize = h.IsFat32 ? 4 : 2;
h.FatOffset = FatxConst.HEADER_SIZE;
long rawFat = (long)h.FatEntrySize * h.MaxClusters;
h.FatSize = ((rawFat + 0xFFF) / 0x1000) * 0x1000;
h.FileAreaOffset = h.FatOffset + h.FatSize;
return h;
}
}
/// <summary>A single directory entry (64 bytes).</summary>
internal sealed class FatxDirent
{
public byte NameLength;
public byte Attributes;
public string Name;
public uint FirstCluster;
public uint FileSize;
public uint CreationTime;
public uint LastWriteTime;
public uint LastAccessTime;
public long Offset; // absolute offset in partition stream
public bool IsDeleted;
public bool IsFree;
public bool IsDirectory { get { return (Attributes & FatxConst.ATTR_DIRECTORY) != 0; } }
public bool IsValid { get { return !IsFree && !IsDeleted && NameLength > 0 && NameLength <= FatxConst.MAX_FILENAME; } }
public static FatxDirent Read(PartitionStream io, long offset)
{
io.SeekTo(offset);
byte[] raw = io.ReadBytes(FatxConst.DIRENT_SIZE);
if (raw.Length < FatxConst.DIRENT_SIZE) return null;
FatxDirent d = new FatxDirent();
d.Offset = offset;
d.NameLength = raw[0];
d.Attributes = raw[1];
if (d.NameLength == FatxConst.DIRENT_NEVER_USED || d.NameLength == FatxConst.DIRENT_NEVER_USED2)
{
d.IsFree = true;
d.Name = "";
return d;
}
if (d.NameLength == FatxConst.DIRENT_DELETED)
{
d.IsDeleted = true;
}
int len = Math.Min((byte)d.NameLength, (byte)FatxConst.MAX_FILENAME);
byte[] nameBytes = new byte[len];
Array.Copy(raw, 2, nameBytes, 0, len);
d.Name = Encoding.ASCII.GetString(nameBytes).TrimEnd('\0', (char)0xFF);
d.FirstCluster = Endian.ReadU32BE(raw, 0x2C);
d.FileSize = Endian.ReadU32BE(raw, 0x30);
d.CreationTime = Endian.ReadU32BE(raw, 0x34);
d.LastWriteTime = Endian.ReadU32BE(raw, 0x38);
d.LastAccessTime = Endian.ReadU32BE(raw, 0x3C);
return d;
}
public void WriteTo(PartitionStream io)
{
byte[] raw = new byte[FatxConst.DIRENT_SIZE];
for (int i = 0; i < raw.Length; i++) raw[i] = 0xFF;
raw[0] = NameLength;
raw[1] = Attributes;
byte[] nb = Encoding.ASCII.GetBytes(Name ?? "");
Array.Copy(nb, 0, raw, 2, Math.Min(nb.Length, FatxConst.MAX_FILENAME));
Endian.WriteU32BE(raw, 0x2C, FirstCluster);
Endian.WriteU32BE(raw, 0x30, FileSize);
Endian.WriteU32BE(raw, 0x34, CreationTime);
Endian.WriteU32BE(raw, 0x38, LastWriteTime);
Endian.WriteU32BE(raw, 0x3C, LastAccessTime);
io.SeekTo(Offset);
io.WriteBytes(raw);
}
public void MarkDeleted(PartitionStream io)
{
io.SeekTo(Offset);
io.WriteBytes(new byte[] { FatxConst.DIRENT_DELETED });
}
public DateTime GetCreationDate()
{
return DosToDateTime(CreationTime);
}
public DateTime GetLastWriteDate()
{
return DosToDateTime(LastWriteTime);
}
/// <summary>
/// uint32 BE = (DOS_date << 16) | DOS_time.
/// FAT/DOS time: bits 15-11 = hour, 10-5 = min, 4-0 = sec/2 (per free60 FATX spec).
/// FAT/DOS date: bits 15-9 = year-1980, 8-5 = month, 4-0 = day.
/// Возвращает DateTime.MinValue, если метка пустая (date==0 && time==0).
/// </summary>
private static DateTime DosToDateTime(uint packed32)
{
uint date = (packed32 >> 16) & 0xFFFF;
uint time = packed32 & 0xFFFF;
if (date == 0 && time == 0) return DateTime.MinValue; // пусто → скроем в UI
int day = (int)(date & 0x1F);
int month = (int)((date >> 5) & 0x0F);
int year = (int)((date >> 9) & 0x7F) + 1980;
int sec2 = (int)(time & 0x1F);
int min = (int)((time >> 5) & 0x3F);
int hour = (int)((time >> 11) & 0x1F);
// защита от мусорных бит (clamp в допустимые диапазоны)
if (month < 1) month = 1; if (month > 12) month = 12;
if (day < 1) day = 1;
if (hour > 23) hour = 23;
if (min > 59) min = 59;
int sec = sec2 * 2; if (sec > 59) sec = 59;
try
{
int daysInMonth = DateTime.DaysInMonth(year, month);
if (day > daysInMonth) day = daysInMonth;
return new DateTime(year, month, day, hour, min, sec);
}
catch
{
return DateTime.MinValue;
}
}
private static DateTime PackedTimeToDateTime(uint packed)
{
try
{
int year = (int)(packed & 0x7F) + 1980;
int month = (int)((packed >> 7) & 0x0F);
int day = (int)((packed >> 11) & 0x1F);
int hour = (int)((packed >> 16) & 0x1F);
int minute = (int)((packed >> 21) & 0x3F);
int sec = (int)((packed >> 27) & 0x1F) * 2;
if (month < 1) month = 1; if (month > 12) month = 12;
if (day < 1) day = 1; if (day > 28) day = 28;
if (hour > 23) hour = 0; if (minute > 59) minute = 0; if (sec > 59) sec = 0;
return new DateTime(year, month, day, hour, minute, sec);
}
catch { return DateTime.MinValue; }
}
}
/// <summary>FATX partition – the main file-system engine.</summary>
internal sealed class FatxPartition : IDisposable
{
public PartitionStream IO;
public FatxHeader Header;
public string Label;
private bool _disposed;
public FatxPartition(PartitionStream io, long partitionOffset, long partitionLength, string label)
{
IO = io;
IO.GlobalOffset = partitionOffset;
Label = label;
Header = FatxHeader.Read(io, partitionLength);
Log.Ok(string.Format("FATX partition '{0}': cluster={1}, FAT{2}, clusters={3}",
label, Header.ClusterSize, Header.IsFat32 ? "32" : "16", Header.MaxClusters));
}
// --- FAT helpers ---
public long ClusterToOffset(uint cluster)
{
return Header.FileAreaOffset + (long)(cluster - 1) * Header.ClusterSize;
}
public uint ReadFatEntry(uint cluster)
{
long off = Header.FatOffset + (long)cluster * Header.FatEntrySize;
IO.SeekTo(off);
byte[] buf = IO.ReadBytes(Header.FatEntrySize);
if (Header.IsFat32)
return Endian.ReadU32BE(buf, 0);
else
return Endian.ReadU16BE(buf, 0);
}
public void WriteFatEntry(uint cluster, uint value)
{
long off = Header.FatOffset + (long)cluster * Header.FatEntrySize;
IO.SeekTo(off);
byte[] buf = new byte[Header.FatEntrySize];
if (Header.IsFat32)
Endian.WriteU32BE(buf, 0, value);
else
Endian.WriteU16BE(buf, 0, (ushort)value);
IO.WriteBytes(buf);
}
/// <summary>Follow cluster chain from startCluster.</summary>
public List<uint> GetClusterChain(uint startCluster)
{
List<uint> chain = new List<uint>();
if (startCluster == 0) return chain;
uint cur = startCluster;
int guard = 0;
int maxGuard = (int)(Header.MaxClusters + 10);
while (cur != 0 && cur != FatxConst.CLUSTER_LAST && cur != FatxConst.CLUSTER_LAST16)
{
if (cur >= Header.MaxClusters)
{
Log.Warn("Cluster chain out of range: " + cur);
break;
}
chain.Add(cur);
uint next = ReadFatEntry(cur);
if (next == cur) break; // infinite loop guard
cur = next;
if (++guard > maxGuard)
{
Log.Warn("Cluster chain too long, breaking.");
break;
}
}
return chain;
}
// --- Directory reading ---
/// <summary>Read all dirents from a cluster chain.</summary>
public List<FatxDirent> ReadDirectory(uint startCluster)
{
List<FatxDirent> entries = new List<FatxDirent>();
List<uint> chain = GetClusterChain(startCluster);
int direntsPerCluster = (int)(Header.ClusterSize / FatxConst.DIRENT_SIZE);
foreach (uint cl in chain)
{
long baseOff = ClusterToOffset(cl);
for (int i = 0; i < direntsPerCluster; i++)
{
long off = baseOff + (long)i * FatxConst.DIRENT_SIZE;
try
{
FatxDirent d = FatxDirent.Read(IO, off);
if (d == null) continue;
if (d.IsFree && d.NameLength == FatxConst.DIRENT_NEVER_USED2)
return entries; // end of directory
entries.Add(d);
}
catch (Exception ex)
{
Log.Debug("Dirent read error at offset " + off + ": " + ex.Message);
}
}
}
return entries;
}
// --- File extraction (large-file safe, buffered) ---
public void ExtractFile(FatxDirent dirent, string destPath, IProgressReporter progress)
{
if (dirent.IsDirectory)
{
ExtractDirectoryRecursive(dirent, destPath, progress);
return;
}
List<uint> chain = GetClusterChain(dirent.FirstCluster);
long totalSize = dirent.FileSize;
long written = 0;
using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.None, FatxConst.IO_BUFFER_SIZE))
{
for (int ci = 0; ci < chain.Count; ci++)
{
long off = ClusterToOffset(chain[ci]);
IO.SeekTo(off);
int toRead = (int)Math.Min(Header.ClusterSize, totalSize - written);
if (toRead <= 0) break;
byte[] buf = new byte[Math.Min(toRead, FatxConst.IO_BUFFER_SIZE)];
int remaining = toRead;
while (remaining > 0)
{
int chunk = Math.Min(remaining, buf.Length);
int got = IO.Read(buf, 0, chunk);
if (got <= 0) break;
fs.Write(buf, 0, got);
remaining -= got;
written += got;
}
if (progress != null && totalSize > 0)
progress.Report((int)(written * 100 / totalSize), written, totalSize);
}
}
Log.Ok("Extracted: " + dirent.Name + " → " + destPath);
}
public void ExtractDirectoryRecursive(FatxDirent dirDirent, string destDir, IProgressReporter progress)
{
if (!Directory.Exists(destDir))
Directory.CreateDirectory(destDir);
List<FatxDirent> entries = ReadDirectory(dirDirent.FirstCluster);
foreach (FatxDirent e in entries)
{
if (!e.IsValid) continue;
string sub = Path.Combine(destDir, SanitizeName(e.Name));
if (e.IsDirectory)
ExtractDirectoryRecursive(e, sub, progress);
else
ExtractFile(e, sub, progress);
}
}
// --- File injection ---
public uint FindFreeCluster(uint startFrom)
{
for (uint c = startFrom; c < Header.MaxClusters; c++)
{
if (ReadFatEntry(c) == FatxConst.CLUSTER_FREE)
return c;
}
throw new IOException("No free clusters available.");
}
public uint[] AllocateChain(int count)
{
uint[] chain = new uint[count];
uint search = 2;
for (int i = 0; i < count; i++)
{
chain[i] = FindFreeCluster(search);
search = chain[i] + 1;
}
// link
for (int i = 0; i < count - 1; i++)
WriteFatEntry(chain[i], chain[i + 1]);
WriteFatEntry(chain[count - 1], FatxConst.CLUSTER_LAST);
return chain;
}
public void FreeChain(uint startCluster)
{
List<uint> chain = GetClusterChain(startCluster);
foreach (uint c in chain)
WriteFatEntry(c, FatxConst.CLUSTER_FREE);
}