b1fafb95d39c56da3f01b4c5f7c6d0b34a43e801
[tpg/acess2.git] / KernelLand / Modules / Filesystems / NTFS / main.c
1 /*
2  * Acess2 - NTFS Driver
3  * By John Hodge (thePowersGang)
4  *
5  * main.c
6  * - Driver core
7  *
8  * Reference: ntfsdoc.pdf
9  */
10 #define DEBUG   1
11 #define VERBOSE 0
12 #include <acess.h>
13 #include <vfs.h>
14 #include "common.h"
15 #include <modules.h>
16 #include <utf16.h>
17
18 // === PROTOTYPES ===
19  int    NTFS_Install(char **Arguments);
20  int    NTFS_Detect(int FD);
21 tVFS_Node       *NTFS_InitDevice(const char *Devices, const char **Options);
22 void    NTFS_Unmount(tVFS_Node *Node);
23 // - MFT Related Functions
24 tNTFS_FILE_Header       *NTFS_GetMFT(tNTFS_Disk *Disk, Uint32 MFTEntry);
25 void    NTFS_ReleaseMFT(tNTFS_Disk *Disk, Uint32 MFTEntry, tNTFS_FILE_Header *Entry);
26 tNTFS_Attrib    *NTFS_GetAttrib(tNTFS_Disk *Disk, Uint32 MFTEntry, int Type, const char *Name, int DesIdx);
27 size_t  NTFS_ReadAttribData(tNTFS_Attrib *Attrib, Uint64 Offset, size_t Length, void *Buffer);
28 void    NTFS_DumpEntry(tNTFS_Disk *Disk, Uint32 Entry);
29
30 // === GLOBALS ===
31 MODULE_DEFINE(0, 0x0A /*v0.1*/, FS_NTFS, NTFS_Install, NULL);
32 tVFS_Driver     gNTFS_FSInfo = {
33         .Name = "ntfs",
34         .Detect = NTFS_Detect,
35         .InitDevice = NTFS_InitDevice,
36         .Unmount = NTFS_Unmount,
37         .GetNodeFromINode = NULL
38 };
39 tVFS_NodeType   gNTFS_DirType = {
40         .TypeName = "NTFS-Dir",
41         .ReadDir = NTFS_ReadDir,
42         .FindDir = NTFS_FindDir,
43         .Close = NULL
44         };
45 tVFS_NodeType   gNTFS_FileType = {
46         .TypeName = "NTFS-File",
47         .Close = NULL
48         };
49
50 tNTFS_Disk      gNTFS_Disks;
51
52 // === CODE ===
53 /**
54  * \brief Installs the NTFS driver
55  */
56 int NTFS_Install(char **Arguments)
57 {
58         VFS_AddDriver( &gNTFS_FSInfo );
59         return 0;
60 }
61
62 /**
63  * \brief Detect if a volume is NTFS
64  */
65 int NTFS_Detect(int FD)
66 {
67         tNTFS_BootSector        bs;
68         VFS_ReadAt(FD, 0, 512, &bs);
69         
70         if( bs.BytesPerSector == 0 || (bs.BytesPerSector & 511) )
71                 return 0;
72
73         Uint64  ncluster = bs.TotalSectorCount / bs.SectorsPerCluster;
74         if( bs.MFTStart >= ncluster || bs.MFTMirrorStart >= ncluster )
75                 return 0;
76
77         if( memcmp(bs.SystemID, "NTFS    ", 8) != 0 )
78                 return 0;
79         
80         return 1;
81 }
82
83 /**
84  * \brief Mount a NTFS volume
85  */
86 tVFS_Node *NTFS_InitDevice(const char *Device, const char **Options)
87 {
88         tNTFS_Disk      *disk;
89         tNTFS_BootSector        bs;
90         
91         disk = calloc( sizeof(tNTFS_Disk), 1 );
92         
93         disk->FD = VFS_Open(Device, VFS_OPENFLAG_READ);
94         if(!disk->FD) {
95                 free(disk);
96                 return NULL;
97         }
98         
99         Log_Debug("FS_NTFS", "&bs = %p", &bs);
100         VFS_ReadAt(disk->FD, 0, 512, &bs);
101         
102         Log_Debug("FS_NTFS", "Jump = %02x%02x%02x",
103                 bs.Jump[0],
104                 bs.Jump[1],
105                 bs.Jump[2]);
106         Log_Debug("FS_NTFS", "SystemID = %02x%02x%02x%02x%02x%02x%02x%02x (%8C)",
107                 bs.SystemID[0], bs.SystemID[1], bs.SystemID[2], bs.SystemID[3],
108                 bs.SystemID[4], bs.SystemID[5], bs.SystemID[6], bs.SystemID[7],
109                 bs.SystemID
110                 );
111         Log_Debug("FS_NTFS", "BytesPerSector = %i", bs.BytesPerSector);
112         Log_Debug("FS_NTFS", "SectorsPerCluster = %i", bs.SectorsPerCluster);
113         Log_Debug("FS_NTFS", "MediaDescriptor = 0x%x", bs.MediaDescriptor);
114         Log_Debug("FS_NTFS", "SectorsPerTrack = %i", bs.SectorsPerTrack);
115         Log_Debug("FS_NTFS", "Heads = %i", bs.Heads);
116         Log_Debug("FS_NTFS", "TotalSectorCount = 0x%llx", bs.TotalSectorCount);
117         Log_Debug("FS_NTFS", "MFTStart = 0x%llx", bs.MFTStart);
118         Log_Debug("FS_NTFS", "MFTMirrorStart = 0x%llx", bs.MFTMirrorStart);
119         Log_Debug("FS_NTFS", "ClustersPerMFTRecord = %i", bs.ClustersPerMFTRecord);
120         Log_Debug("FS_NTFS", "ClustersPerIndexRecord = %i", bs.ClustersPerIndexRecord);
121         Log_Debug("FS_NTFS", "SerialNumber = 0x%llx", bs.SerialNumber);
122         
123         disk->ClusterSize = bs.BytesPerSector * bs.SectorsPerCluster;
124         Log_Debug("NTFS", "Cluster Size = %i KiB", disk->ClusterSize/1024);
125         disk->MFTBase = bs.MFTStart;
126         Log_Debug("NTFS", "MFT Base = %i", disk->MFTBase);
127         Log_Debug("NTFS", "TotalSectorCount = 0x%x", bs.TotalSectorCount);
128         
129         if( bs.ClustersPerMFTRecord < 0 ) {
130                 disk->MFTRecSize = 1 << (-bs.ClustersPerMFTRecord);
131         }
132         else {
133                 disk->MFTRecSize = bs.ClustersPerMFTRecord * disk->ClusterSize;
134         }
135         //NTFS_DumpEntry(disk, 0);      // $MFT
136         //NTFS_DumpEntry(disk, 3);      // $VOLUME
137
138         disk->InodeCache = Inode_GetHandle();
139         
140         disk->MFTDataAttr = NULL;
141         disk->MFTDataAttr = NTFS_GetAttrib(disk, 0, NTFS_FileAttrib_Data, "", 0);
142         NTFS_DumpEntry(disk, 5);        // .
143
144         disk->RootDir.I30Root = NTFS_GetAttrib(disk, 5, NTFS_FileAttrib_IndexRoot, "$I30", 0);
145         disk->RootDir.I30Allocation = NTFS_GetAttrib(disk, 5, NTFS_FileAttrib_IndexAllocation, "$I30", 0);
146         disk->RootDir.Node.Inode = 5;   // MFT Ent #5 is filesystem root
147         disk->RootDir.Node.ImplPtr = disk;
148         disk->RootDir.Node.Type = &gNTFS_DirType;
149         disk->RootDir.Node.Flags = VFS_FFLAG_DIRECTORY;
150         
151         disk->RootDir.Node.UID = 0;
152         disk->RootDir.Node.GID = 0;
153         
154         disk->RootDir.Node.NumACLs = 1;
155         disk->RootDir.Node.ACLs = &gVFS_ACL_EveryoneRX;
156
157         #if 0
158         {
159                 // Read from allocation
160                 char buf[disk->ClusterSize];
161                 size_t len = NTFS_ReadAttribData(disk->RootDir.I30Allocation, 0, sizeof(buf), buf);
162                 Debug_HexDump("RootDir allocation", buf, len);
163         }
164         #endif
165
166         return &disk->RootDir.Node;
167 }
168
169 /**
170  * \brief Unmount an NTFS Disk
171  */
172 void NTFS_Unmount(tVFS_Node *Node)
173 {
174         tNTFS_Disk      *Disk = Node->ImplPtr;
175         VFS_Close(Disk->FD);
176         free(Disk);
177 }
178
179 tNTFS_FILE_Header *NTFS_GetMFT(tNTFS_Disk *Disk, Uint32 MFTEntry)
180 {
181         void    *ret = malloc( Disk->MFTRecSize );
182         if(!ret) {
183                 Log_Warning("FS_NTFS", "malloc() fail!");
184                 return NULL;
185         }
186         
187         // NOTE: The MFT is a file, and can get fragmented
188         if( !Disk->MFTDataAttr ) {
189                 VFS_ReadAt( Disk->FD,
190                         Disk->MFTBase * Disk->ClusterSize + MFTEntry * Disk->MFTRecSize,
191                         Disk->MFTRecSize,
192                         ret);
193         }
194         else {
195                 NTFS_ReadAttribData(Disk->MFTDataAttr, MFTEntry * Disk->MFTRecSize, Disk->MFTRecSize, ret);
196         }
197         
198         return ret;
199 }
200
201 void NTFS_ReleaseMFT(tNTFS_Disk *Disk, Uint32 MFTEntry, tNTFS_FILE_Header *Entry)
202 {
203         free(Entry);
204 }
205
206 static inline Uint64 _getVariableLengthInt(const void *Ptr, int Length, int bExtend)
207 {
208         const Uint8     *data = Ptr;
209         Uint64  bits = 0;
210         for( int i = 0; i < Length; i ++ )
211                 bits |= (Uint64)data[i] << (i*8);
212         if( bExtend && Length && data[Length-1] & 0x80 ) {
213                 for( int i = Length; i < 8; i ++ )
214                         bits |= 0xFF << (i*8);
215         }
216         return bits;    // 
217 }
218
219 const void *_GetDataRun(const void *ptr, const void *limit, Uint64 LastLCN, Uint64 *Count, Uint64 *LCN)
220 {
221         // Clean exit?
222         if( ptr == limit ) {
223                 LOG("Clean end of list");
224                 return NULL;
225         }
226         
227         const Uint8     *data = ptr;
228         
229         // Offset size
230         Uint8   ofsSize = data[0] >> 4;
231         Uint8   lenSize = data[0] & 0xF;
232         LOG("ofsSize = %i, lenSize = %i", ofsSize, lenSize);
233         if( ofsSize > 8 )
234                 return NULL;
235         if( lenSize > 8 || lenSize < 1 )
236                 return NULL;
237         if( data + 1 + ofsSize + lenSize > (const Uint8*)limit )
238                 return NULL;
239         
240         if( Count ) {
241                 *Count = _getVariableLengthInt(data + 1, lenSize, 0);
242         }
243         if( LCN ) {
244                 *LCN = LastLCN + (Sint64)_getVariableLengthInt(data + 1 + lenSize, ofsSize, 1);
245         }
246         
247         return data + 1 + ofsSize + lenSize;
248 }
249
250 tNTFS_Attrib *NTFS_GetAttrib(tNTFS_Disk *Disk, Uint32 MFTEntry, int Type, const char *Name, int DesIdx)
251 {
252         ENTER("pDisk xMFTEntry xType sName iDesIdx",
253                 Disk, MFTEntry, Type, Name, DesIdx);
254          int    curIdx = 0;
255         // TODO: Scan cache of attributes
256         
257         // Load MFT entry
258         tNTFS_FILE_Header *hdr = NTFS_GetMFT(Disk, MFTEntry);
259         LOG("hdr = %p", hdr);
260
261         tNTFS_FILE_Attrib       *attr;
262         for( size_t ofs = hdr->FirstAttribOfs; ofs < hdr->RecordSize; ofs += attr->Size )
263         {
264                 attr = (void*)( (tVAddr)hdr + ofs );
265                 // Sanity #1: Type
266                 if( ofs + 4 > hdr->RecordSize )
267                         break ;
268                 // End-of-list?
269                 if( attr->Type == 0xFFFFFFFF )
270                         break;
271                 // Sanity #2: Type,Size
272                 if( ofs + 8 > hdr->RecordSize )
273                         break;
274                 // Sanity #3: Reported size
275                 if( attr->Size < sizeof(attr->Resident) )
276                         break;
277                 // Sanity #4: Reported size fits
278                 if( ofs + attr->Size > hdr->RecordSize )
279                         break;
280                 
281                 // - Chceck if this attribute is the one requested
282                 LOG("Type check %x == %x", attr->Type, Type);
283                 if( attr->Type != Type )
284                         continue;
285                 if( Name ) {
286                         LOG("Name check = '%s'", Name);
287                         const void      *name16 = (char*)attr + attr->NameOffset;
288                         if( UTF16_CompareWithUTF8(attr->NameLength, name16, Name) != 0 )
289                                 continue ;
290                 }
291                 LOG("Idx check %i", curIdx);
292                 if( curIdx++ != DesIdx )
293                         continue ;
294
295                 // - Construct (and cache) attribute description
296                 ASSERT(attr->NameOffset % 1 == 0);
297                 Uint16  *name16 = (Uint16*)attr + attr->NameOffset/2;
298                 size_t  namelen = UTF16_ConvertToUTF8(0, NULL, attr->NameLength, name16);
299                 size_t  edatalen = (attr->NonresidentFlag ? 0 : attr->Resident.AttribLen*4);
300                 tNTFS_Attrib *ret = malloc( sizeof(tNTFS_Attrib) + namelen + 1 + edatalen );
301                 if(!ret) {
302                         LEAVE('n');
303                         return NULL;
304                 }
305                 if( attr->NonresidentFlag )
306                         ret->Name = (void*)(ret + 1);
307                 else {
308                         ret->ResidentData = ret + 1;
309                         ret->Name = (char*)ret->ResidentData + edatalen;
310                 }
311                 
312                 ret->Disk = Disk;
313                 ret->Type = attr->Type;
314                 UTF16_ConvertToUTF8(namelen+1, ret->Name, attr->NameLength, name16);
315                 ret->IsResident = !(attr->NonresidentFlag);
316
317                 LOG("Creating with %x '%s'", ret->Type, ret->Name);
318
319                 if( attr->NonresidentFlag )
320                 {
321                         ret->DataSize = attr->NonResident.RealSize;
322                         ret->NonResident.CompressionUnitL2Size = attr->NonResident.CompressionUnitSize;
323                         ret->NonResident.FirstPopulatedCluster = attr->NonResident.StartingVCN;
324                         // Count data runs
325                         const char *limit = (char*)attr + attr->Size;
326                          int    nruns = 0;
327                         const char *datarun = (char*)attr + attr->NonResident.DataRunOfs;
328                         while( (datarun = _GetDataRun(datarun, limit, 0, NULL, NULL)) )
329                                 nruns ++;
330                         LOG("nruns = %i", nruns);
331                         // Allocate data runs
332                         ret->NonResident.nRuns = nruns;
333                         ret->NonResident.Runs = malloc( sizeof(tNTFS_AttribDataRun) * nruns );
334                          int    i = 0;
335                         datarun = (char*)attr + attr->NonResident.DataRunOfs;
336                         Uint64  lastLCN = 0;
337                         while( datarun && i < nruns )
338                         {
339                                 tNTFS_AttribDataRun     *run = &ret->NonResident.Runs[i];
340                                 datarun = _GetDataRun(datarun,limit, lastLCN, &run->Count, &run->LCN);
341                                 LOG("Run %i: %llx+%llx", i, run->LCN, run->Count);
342                                 lastLCN = run->LCN;
343                                 i ++;
344                         }
345                 }
346                 else
347                 {
348                         memcpy(ret->ResidentData, (char*)attr + attr->Resident.AttribOfs, edatalen);
349                 }
350                 
351                 LEAVE('p', ret);
352                 return ret;
353         }
354
355         NTFS_ReleaseMFT(Disk, MFTEntry, hdr);
356         LEAVE('n');
357         return NULL;
358 }
359
360 size_t NTFS_ReadAttribData(tNTFS_Attrib *Attrib, Uint64 Offset, size_t Length, void *Buffer)
361 {
362         if( Offset >= Attrib->DataSize )
363                 return 0;
364         if( Length > Attrib->DataSize )
365                 Length = Attrib->DataSize;
366         if( Offset + Length > Attrib->DataSize )
367                 Length = Attrib->DataSize - Offset;
368                 
369         if( Attrib->IsResident )
370         {
371                 memcpy(Buffer, Attrib->ResidentData, Length);
372                 return Length;
373         }
374         else
375         {
376                 size_t  ret = 0;
377                 tNTFS_Disk      *Disk = Attrib->Disk;
378                 Uint64  first_cluster = Offset / Disk->ClusterSize;
379                 size_t  cluster_ofs = Offset % Disk->ClusterSize;
380                 if( first_cluster < Attrib->NonResident.FirstPopulatedCluster ) {
381                         Log_Warning("NTFS", "TODO: Ofs < FirstVCN");
382                 }
383                 first_cluster -= Attrib->NonResident.FirstPopulatedCluster;
384                 if( Attrib->NonResident.CompressionUnitL2Size )
385                 {
386                         // TODO: Compression
387                         Log_Warning("NTFS", "Compression unsupported");
388                         // NOTE: Compressed blocks show up in pairs of runs
389                         // - The first contains the compressed data
390                         // - The second is a placeholder 'sparse' (LCN=0) to align to the compression unit
391                 }
392                 else
393                 {
394                         // Iterate through data runs until the desired run is located
395                         for( int i = 0; i < Attrib->NonResident.nRuns && Length; i ++ )
396                         {
397                                 tNTFS_AttribDataRun     *run = &Attrib->NonResident.Runs[i];
398                                 if( first_cluster > run->Count ) {
399                                         first_cluster -= run->Count;
400                                         continue ;
401                                 }
402                                 size_t  avail_bytes = (run->Count-first_cluster)*Disk->ClusterSize - cluster_ofs;
403                                 if( avail_bytes > Length )
404                                         avail_bytes = Length;
405                                 // Read from this extent
406                                 if( run->LCN == 0 ) {
407                                         memset(Buffer, 0, avail_bytes);
408                                 }
409                                 else {
410                                         VFS_ReadAt(Disk->FD,
411                                                 (run->LCN + first_cluster)*Disk->ClusterSize + cluster_ofs,
412                                                 avail_bytes,
413                                                 Buffer
414                                                 );
415                                 }
416                                 Length -= avail_bytes;
417                                 Buffer += avail_bytes;
418                                 ret += avail_bytes;
419                                 first_cluster = 0;
420                                 cluster_ofs = 0;
421                                 continue ;
422                         }
423                 }
424                 return ret;
425         }
426 }
427
428 /**
429  * \brief Dumps a MFT Entry
430  */
431 void NTFS_DumpEntry(tNTFS_Disk *Disk, Uint32 Entry)
432 {
433         tNTFS_FILE_Attrib       *attr;
434          int    i;
435         
436         tNTFS_FILE_Header       *hdr = malloc( Disk->MFTRecSize );
437         if(!hdr) {
438                 Log_Warning("FS_NTFS", "malloc() fail!");
439                 return ;
440         }
441         
442         VFS_ReadAt( Disk->FD,
443                 Disk->MFTBase * Disk->ClusterSize + Entry * Disk->MFTRecSize,
444                 Disk->MFTRecSize,
445                 hdr);
446         
447         Log_Debug("FS_NTFS", "MFT Entry #%i", Entry);
448         Log_Debug("FS_NTFS", "- Magic = 0x%08x (%4C)", hdr->Magic, &hdr->Magic);
449         Log_Debug("FS_NTFS", "- UpdateSequenceOfs = 0x%x", hdr->UpdateSequenceOfs);
450         Log_Debug("FS_NTFS", "- UpdateSequenceSize = 0x%x", hdr->UpdateSequenceSize);
451         Log_Debug("FS_NTFS", "- LSN = 0x%x", hdr->LSN);
452         Log_Debug("FS_NTFS", "- SequenceNumber = %i", hdr->SequenceNumber);
453         Log_Debug("FS_NTFS", "- HardLinkCount = %i", hdr->HardLinkCount);
454         Log_Debug("FS_NTFS", "- FirstAttribOfs = 0x%x", hdr->FirstAttribOfs);
455         Log_Debug("FS_NTFS", "- Flags = 0x%x", hdr->Flags);
456         Log_Debug("FS_NTFS", "- RecordSize = 0x%x", hdr->RecordSize);
457         Log_Debug("FS_NTFS", "- RecordSpace = 0x%x", hdr->RecordSpace);
458         Log_Debug("FS_NTFS", "- Reference = 0x%llx", hdr->Reference);
459         Log_Debug("FS_NTFS", "- NextAttribID = 0x%04x", hdr->NextAttribID);
460         
461         attr = (void*)( (char*)hdr + hdr->FirstAttribOfs );
462         i = 0;
463         while( (tVAddr)attr < (tVAddr)hdr + hdr->RecordSize )
464         {
465                 if(attr->Type == 0xFFFFFFFF)    break;
466                 Log_Debug("FS_NTFS", "- Attribute %i", i ++);
467                 Log_Debug("FS_NTFS", " > Type = 0x%x", attr->Type);
468                 Log_Debug("FS_NTFS", " > Size = 0x%x", attr->Size);
469                 Log_Debug("FS_NTFS", " > ResidentFlag = 0x%x", attr->NonresidentFlag);
470                 Log_Debug("FS_NTFS", " > NameLength = %i", attr->NameLength);
471                 Log_Debug("FS_NTFS", " > NameOffset = 0x%x", attr->NameOffset);
472                 Log_Debug("FS_NTFS", " > Flags = 0x%x", attr->Flags);
473                 Log_Debug("FS_NTFS", " > AttributeID = 0x%x", attr->AttributeID);
474                 {
475                         Uint16  *name16 = (void*)((char*)attr + attr->NameOffset);
476                         size_t  len = UTF16_ConvertToUTF8(0, NULL, attr->NameLength, name16);
477                         char    name[len+1];
478                         UTF16_ConvertToUTF8(len+1, name, attr->NameLength, name16);
479                         Log_Debug("FS_NTFS", " > Name = '%s'", name);
480                 }
481                 if( !attr->NonresidentFlag ) {
482                         Log_Debug("FS_NTFS", " > AttribLen = 0x%x", attr->Resident.AttribLen);
483                         Log_Debug("FS_NTFS", " > AttribOfs = 0x%x", attr->Resident.AttribOfs);
484                         Log_Debug("FS_NTFS", " > IndexedFlag = 0x%x", attr->Resident.IndexedFlag);
485                         Debug_HexDump("FS_NTFS",
486                                 (void*)( (tVAddr)attr + attr->Resident.AttribOfs ),
487                                 attr->Resident.AttribLen
488                                 );
489                 }
490                 else {
491                         Log_Debug("FS_NTFS", " > StartingVCN = 0x%llx", attr->NonResident.StartingVCN);
492                         Log_Debug("FS_NTFS", " > LastVCN = 0x%llx", attr->NonResident.LastVCN);
493                         Log_Debug("FS_NTFS", " > DataRunOfs = 0x%x", attr->NonResident.DataRunOfs);
494                         Log_Debug("FS_NTFS", " > CompressionUnitSize = 0x%x", attr->NonResident.CompressionUnitSize);
495                         Log_Debug("FS_NTFS", " > AllocatedSize = 0x%llx", attr->NonResident.AllocatedSize);
496                         Log_Debug("FS_NTFS", " > RealSize = 0x%llx", attr->NonResident.RealSize);
497                         Log_Debug("FS_NTFS", " > InitiatedSize = 0x%llx", attr->NonResident.InitiatedSize);
498                         Debug_HexDump("FS_NTFS",
499                                 (char*)attr + attr->NonResident.DataRunOfs,
500                                 attr->Size - attr->NonResident.DataRunOfs
501                                 );
502                 }
503                 
504                 attr = (void*)( (tVAddr)attr + attr->Size );
505         }
506         
507         free(hdr);
508 }

UCC git Repository :: git.ucc.asn.au