d0f2f499b157cbb4eb7c0c2c96f5d38d52e69c23
[virt-df.git] / lib / diskimage_ntfs.ml
1 (* 'df' command for virtual domains.
2    (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
3    http://libvirt.org/
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19    Support for NTFS.
20 *)
21
22 open Unix
23 open Printf
24
25 open Diskimage_impl
26 open Int63.Operators
27
28 let id = "ntfs"
29
30 (* Type of the private data, basically all the metadata that we
31  * read from the NTFS volume.
32  *)
33 type ntfs_fs = {
34   ntfs_dev : device;                    (* Device. *)
35   ntfs_blocksize : int63;               (* Blocksize (cluster size) *)
36   ntfs_mft_lcn : int63;                 (* MFT location (bytes) *)
37   ntfs_mft_size : int63;                (* MFT size (bytes) *)
38   ntfs_mft_records : ntfs_mft_record list; (* Files in MFT *)
39 }
40 and ntfs_mft_record = {
41   ntfs_filename : ntfs_filename option; (* Filename, if present. *)
42   ntfs_info : ntfs_info option;         (* Standard information, if present. *)
43   ntfs_data : ntfs_data option;         (* $Data stream, if present. *)
44 }
45 and ntfs_filename = {
46   ntfs_name : string;                   (* Filename (UTF-8 encoded). *)
47 }
48 and ntfs_info = {
49   ntfs_creation_time : int64;
50   ntfs_last_data_change_time : int64;
51   ntfs_last_mft_change_time : int64;
52   ntfs_last_access_time : int64;
53 }
54 and ntfs_data = {
55   ntfs_data_size : int63;               (* Actual size of data. *)
56   ntfs_runlist : ntfs_runentry list;    (* Runlist. *)
57 }
58 and ntfs_runentry =
59     (* VCN start,size => LCN / None if sparse hole *)
60     (int63 * int63)   *  int63 option
61
62 (* Private data functions. *)
63 let attach_private_data, get_private_data =
64   private_data_functions (fun {fs_cb = {fs_cb_uq = u}} -> u)
65
66 (* Probe for an NTFS filesystem on this device. *)
67 let rec probe dev =
68   let fs = probe_superblock dev in
69   fs
70
71 and probe_superblock dev =
72   (* Load the boot sector / superblock. *)
73   let bits = dev#read_bitstring ~^0 ~^512 in
74
75   (* Most of this data comes from ntfsprogs' layout.h header file. *)
76   bitmatch bits with
77   | { _ : 24;                           (* Jump to boot up code. *)
78       "NTFS    " : 64 : string;         (* NTFS OEM ID (magic). *)
79       bytes_per_sector : 16 : littleendian;
80       sectors_per_cluster : 8 : littleendian;
81       _ : 16;                           (* Reserved sectors - unused. *)
82       _ : 8;                            (* FATs - unused. *)
83       _ : 16;                           (* Root entries - unused. *)
84       _ : 16;                           (* Sectors - unused. *)
85       _ : 8;                            (* Media type, probably 'f8' = HDD *)
86       _ : 16;                           (* Sectors per FAT - unused. *)
87       _ : 16;                           (* Sectors per track. *)
88       _ : 16;                           (* Heads. *)
89       _ : 32;                           (* Hidden sectors. *)
90       _ : 32;                           (* Large sectors. *)
91       _ : 8;                            (* Physical drive, 0 = FDD, 0x80 = HDD*)
92       _ : 8;                            (* Current head. *)
93       _ : 8;                            (* Extended boot signature. *)
94       _ : 8;                            (* Reserved. *)
95       number_of_sectors : 64 : littleendian;
96       mft_lcn : 64 : littleendian;      (* MFT location in clusters. *)
97       mftmirr_lcn : 64 : littleendian;  (* MFT mirror location. *)
98       clusters_per_mft_record : 8;
99       _ : 24;
100       clusters_per_index_record : 8;
101       _ : 24;
102       volume_serial_number : 64 : littleendian;
103       checksum : 32 : littleendian;     (* Boot sector checksum. *)
104       code : 8 * 426 : bitstring;       (* Boot code. *)
105       0x55AA : 16 } ->                  (* End of bootsector magic. *)
106
107       let blocksize = bytes_per_sector * sectors_per_cluster in
108
109       if !debug then
110         eprintf "%s: NTFS boot sector with blocksize = %d, serial = %Lx\n%!"
111           dev#name blocksize volume_serial_number;
112
113       let blocksize = Int63.of_int blocksize in
114       let number_of_sectors = Int63.of_int64 number_of_sectors in
115
116       (* The blocksize of the filesystem is likely to be quite different
117        * from that of the underlying device, so create an overlay device
118        * with the natural filesystem blocksize.
119        *)
120       let fs_dev = new blocksize_overlay blocksize dev in
121
122       (* Get the location and size of the Master File Table. *)
123       let mft_lcn = Int63.of_int64 mft_lcn *^ blocksize in
124       let mft_size = Int63.of_int clusters_per_mft_record *^ blocksize in
125
126       let mft = parse_mft dev mft_lcn mft_size in
127
128       let ntfs = {
129         ntfs_dev = fs_dev;
130         ntfs_blocksize = blocksize;
131         ntfs_mft_lcn = mft_lcn;
132         ntfs_mft_size = mft_size;
133         ntfs_mft_records = mft
134       } in
135
136       (* Query free space.  I cannot find any metadata in the NTFS
137        * structures which records free space directly, so instead we
138        * need to read the $Bitmap::$Data (bitmap of allocated LCNs).
139        *)
140       let blocks_used, blocks_avail = parse_bitmap_freespace ntfs in
141
142       (* Create a filesystem structure. *)
143       let fs = {
144         fs_cb = callbacks ();
145         fs_dev = fs_dev;
146         fs_blocksize = blocksize;
147         fs_blocks_total = number_of_sectors *^ bytes_per_sector /^ blocksize;
148         fs_is_swap = false;
149         fs_blocks_reserved = ~^0;       (* XXX MFT, bitmap are "reserved" *)
150         fs_blocks_avail = blocks_avail;
151         fs_blocks_used = blocks_used;
152         fs_inodes_total = ~^0;          (* XXX MFT records are like inodes *)
153         fs_inodes_reserved = ~^0;
154         fs_inodes_avail = ~^0;
155         fs_inodes_used = ~^0;
156       } in
157
158       attach_private_data fs ntfs;
159       fs
160
161   | { _ } -> raise Not_found            (* Not an NTFS boot sector. *)
162
163 and parse_mft dev mft_lcn mft_size =
164   (* Read the whole of the MFT (which is an array of MFT records) ... *)
165   let bits = dev#read_bitstring mft_lcn mft_size in
166
167   (* ... and turn the MFT into records. *)
168   let records = parse_mft_records bits in
169   records
170
171 and parse_mft_records bits =
172   bitmatch bits with
173   | { "FILE" : 32 : string;
174       (* Assume 3 USAs starting at offset 0x30. XXX? *)
175       0x30 : 16 : littleendian;
176       0x03 : 16 : littleendian;
177       _ : 64;                           (* lsn *)
178       _ : 16;                           (* sequence_number *)
179       _ : 16;                           (* link_count *)
180       _ : 16;                           (* attrs_offset *)
181       _ : 16;                           (* MFT_RECORD_FLAGS *)
182       bytes_in_use : 32 : littleendian;
183       record_size : 32 : littleendian;
184       _ : 64;                           (* base_mft_record *)
185       _ : 16;                           (* next_attr_instance *)
186       _ : 16;                           (* reserved *)
187       _ : 32;                           (* mft_record_number *)
188       _ : 64;                           (* USN, 3 * USAs -- see above. *)
189
190       (* The attributes.  Subtract header size (0x30 bytes)
191        * and space for the USN/USAs (8 bytes).
192        *)
193       attrs : (Int32.to_int record_size - 0x30 - 8)*8 : bitstring;
194
195       (* Subsequent MFT records: *)
196       rest : -1 : bitstring } ->
197
198       if !debug then
199         eprintf "got an MFT record, now parsing attributes ...\n%!";
200
201       let mft_record = {
202         ntfs_filename = None;
203         ntfs_info = None;
204         ntfs_data = None
205       } in
206       let mft_record = parse_attrs attrs mft_record in
207
208       mft_record :: parse_mft_records rest (* loop rest of MFT records *)
209
210   (* Just assume that the end of the list of MFT records
211    * is marked by all zeroes.  This seems to be the
212    * case, but not sure if it is generally true.
213    * XXX?
214    *)
215   | { 0x00000000_l : 32 } -> []
216
217   | { _ } -> []
218
219 and parse_attrs attrs mft_record =
220   (* Parse the MFT record attributes. *)
221   bitmatch attrs with
222   | { 0xFFFFFFFF_l : 32 : littleendian } -> (* AT_END *)
223       if !debug then
224         eprintf "found AT_END, end of attributes\n%!";
225       mft_record
226
227   | { attr_type : 32 : littleendian;
228       attr_size : 32 : littleendian;
229       0 : 8;                         (* means attribute is resident *)
230       pad : 24*8 - 8 - 64 : bitstring; (* actually meaningful *)
231       attr : (Int32.to_int attr_size - 24) * 8 : bitstring;
232       rest : -1 : bitstring } ->
233
234       let mft_record = parse_resident_attr attr_type attr mft_record in
235       parse_attrs rest mft_record
236
237   | { attr_type : 32 : littleendian;
238       attr_size : 32 : littleendian;
239       1 : 8;                            (* non-resident attribute *)
240       0 : 8;                            (* name length, assume unnamed *)
241       _ : 16;                           (* name offset *)
242       _ : 16;                           (* flags *)
243       _ : 16;                           (* instance number *)
244       0L : 64 : littleendian;           (* lowest VCN, assume single extent *)
245       highest_vcn : 64 : littleendian;  (* size in clusters - 1 *)
246       0x40 : 16 : littleendian;         (* mapping pairs offset *)
247       0 : 8;                            (* assume not compressed *)
248       pad : 40 : bitstring;             (* padding *)
249       allocated_size : 64 : littleendian; (* allocate size on disk *)
250       data_size : 64 : littleendian;      (* byte size of the attribute *)
251       initialized_size : 64 : littleendian;
252
253       (* Table of virtual clusters to logical clusters. *)
254       mapping_pairs : (Int32.to_int attr_size - 0x40) * 8 : bitstring;
255
256       rest : -1 : bitstring } ->
257
258       let data_size = Int63.of_int64 data_size in
259
260       let mft_record =
261         parse_nonresident_attr attr_type highest_vcn
262           allocated_size data_size initialized_size
263           mapping_pairs mft_record in
264
265       parse_attrs rest mft_record
266
267   (* Not matched above, so we don't know how to parse this attribute, but
268    * there is still enough information to skip to the next one.
269    *)
270   | { attr_type : 32 : littleendian;
271       attr_size : 32 : littleendian;
272       pad : (Int32.to_int attr_size - 8) * 8 : bitstring;
273       rest : -1 : bitstring } ->
274
275       if !debug then
276         eprintf "cannot parse MFT attribute entry, attr_type = %lx\n%!"
277           attr_type;
278
279       parse_attrs rest mft_record
280
281   (* Otherwise unparsable & unskippable attribute entry. *)
282   | { _ } ->
283       if !debug then
284         eprintf "corrupt MFT attribute entry\n%!";
285       mft_record
286
287 and parse_resident_attr attr_type attr mft_record =
288   match attr_type with
289   | 0x10_l ->                           (* AT_STANDARD_INFORMATION *)
290       (bitmatch attr with
291        | { creation_time : 64;
292            last_data_change_time : 64;
293            last_mft_change_time : 64;
294            last_access_time : 64
295            (* other stuff follows, just ignore it *) } ->
296
297            let info = {
298              ntfs_creation_time = creation_time;
299              ntfs_last_data_change_time = last_data_change_time;
300              ntfs_last_mft_change_time = last_mft_change_time;
301              ntfs_last_access_time = last_access_time
302            } in
303            { mft_record with ntfs_info = Some info }
304
305        | { _ } ->
306            if !debug then
307              eprintf "cannot parse AT_STANDARD_INFORMATION\n%!";
308            mft_record
309       );
310
311   | 0x30_l ->                           (* AT_FILE_NAME *)
312       (bitmatch attr with
313        | { _ : 64;                      (* parent directory ref *)
314            _ : 64;                      (* creation time *)
315            _ : 64;                      (* last change time *)
316            _ : 64;                      (* last MFT change time *)
317            _ : 64;                      (* last access time *)
318            _ : 64;                      (* allocated size *)
319            _ : 64;                      (* data size *)
320            _ : 32;
321            _ : 32;
322            name_len : 8;
323            name_type_flags : 8;
324            name : name_len*16 : string } ->
325
326            let name = ucs2_to_utf8 name name_len in
327            let filename = {
328              ntfs_name = name
329            } in
330            { mft_record with ntfs_filename = Some filename }
331
332        | { _ } ->
333            if !debug then
334              eprintf "cannot parse AT_FILE_NAME\n%!";
335            mft_record
336       );
337
338   | _ ->                                (* unknown attribute - just ignore *)
339       if !debug then
340         eprintf "unknown resident attribute %lx\n%!" attr_type;
341       mft_record
342
343 and parse_nonresident_attr attr_type highest_vcn
344     allocated_size data_size initialized_size
345     mapping_pairs mft_record =
346   match attr_type with
347   | 0x80_l ->                           (* AT_DATA, ie. the $Data stream *)
348       let lowest_vcn = ~^0 (* see assumption above *) in
349       let runlist = parse_runlist lowest_vcn ~^0 mapping_pairs in
350       if !debug then (
351         eprintf "AT_DATA: runlist is:\n";
352         List.iter (
353           function
354           | ((vcn, deltavcn), Some lcn) ->
355             eprintf "\tVCNs %s..%s -> LCN %s\n"
356               (Int63.to_string vcn) (Int63.to_string (vcn +^ deltavcn -^ ~^1))
357               (Int63.to_string lcn)
358           | ((vcn, deltavcn), None) ->
359             eprintf "\tVCNs %s..%s -> sparse hole\n"
360               (Int63.to_string vcn) (Int63.to_string (vcn +^ deltavcn -^ ~^1))
361         ) runlist
362       );
363
364       let data = {
365         ntfs_data_size = data_size;
366         ntfs_runlist = runlist
367       } in
368       { mft_record with ntfs_data = Some data }
369
370   | _ ->
371       if !debug then
372         eprintf "unknown non-resident attribute %lx\n%!" attr_type;
373       mft_record
374
375 (* mapping_pairs is not straightforward and not documented well.  See
376  * ntfsprogs libntfs/runlist.c:ntfs_mapping_pairs_decompress
377  *)
378 and parse_runlist vcn lcn bits =
379   bitmatch bits with
380   | { 0 : 8 } ->                        (* end of table *)
381       []
382
383   | { 0 : 4;
384       vcnlen : 4;
385       deltavcn : vcnlen * 8 : littleendian;
386       rest : -1 : bitstring
387     } when vcnlen >= 1 && vcnlen <= 4 ->
388
389       let deltavcn = Int63.of_int64 deltavcn in
390
391       (* This is a sparse file hole. *)
392       ((vcn, deltavcn), None) ::
393         parse_runlist (vcn +^ deltavcn) lcn rest
394
395   | { (* Really these fields are signed, but we'll just limit it to
396        * sensible values in the when clause instead.
397        *)
398       lcnlen : 4;
399       vcnlen : 4;
400       deltavcn : vcnlen * 8 : littleendian;
401       deltalcn : lcnlen * 8 : littleendian;
402       rest : -1 : bitstring
403     } when (vcnlen >= 1 && vcnlen <= 4) && (lcnlen >= 1 || lcnlen <= 4) ->
404
405       let deltavcn = Int63.of_int64 deltavcn in
406       let deltalcn = Int63.of_int64 deltalcn in (* XXX signed *)
407
408       let lcn = lcn +^ deltalcn in
409
410       ((vcn, deltavcn), Some lcn) ::
411         parse_runlist (vcn +^ deltavcn) lcn rest
412
413   | { _ } ->
414       if !debug then (
415         eprintf "unknown field in the runlist\n%!";
416         Bitmatch.hexdump_bitstring Pervasives.stderr bits
417       );
418       []
419
420 (* Poor man's little-endian UCS-2 to UTF-8 conversion.
421  * XXX Should use Camomile.
422  *)
423 and ucs2_to_utf8 name len =
424   (* Calculate length of final string. *)
425   let outlen = ref 0 in
426   let j = ref 0 in
427   for i = 0 to len-1 do
428     let j' = !j in
429     j := j' + 2;
430     let c0 = Char.code name.[j'] and c1 = Char.code name.[j'+1] in
431     let c = c0 + c1 * 256 in
432     if c < 128 then incr outlen
433     else if c < 0x800 then outlen := !outlen + 2
434     else outlen := !outlen + 3
435   done;
436   let outstr = String.create !outlen in
437   j := 0; outlen := 0;
438   for i = 0 to len-1 do
439     let j' = !j in
440     j := j' + 2;
441     let c0 = Char.code name.[j'] and c1 = Char.code name.[j'+1] in
442     let c = c0 + c1 * 256 in
443     if c < 128 then (
444       outstr.[!outlen] <- Char.chr c;
445       incr outlen
446     ) else if c < 0x800 then (
447       outstr.[!outlen] <- Char.chr (0b11000000 lor (c lsr 6));
448       outstr.[!outlen+1] <- Char.chr (0b10000000 lor (c land 0b00111111));
449       outlen := !outlen + 2
450     ) else (
451       outstr.[!outlen] <- Char.chr (0b11100000 lor (c lsr 12));
452       outstr.[!outlen+1] <- Char.chr (0b10000000 lor ((c lsr 6) lor 0b00111111));
453       outstr.[!outlen+2] <- Char.chr (0b10000000 lor (c land 0b00111111));
454       outlen := !outlen + 3
455     )
456   done;
457   outstr
458
459 (* Parse $Bitmap::$Data to get free/used.  Returns (used, free) blocks. *)
460 and parse_bitmap_freespace ntfs =
461   (* Can throw Not_found - allow that to escape because we don't
462    * expect an NTFS filesystem without this magic file.
463    *)
464   let file = find_system_file ntfs "$Bitmap" in
465
466   (* Count used/free bits. *)
467   let used = ref ~^0 and free = ref ~^0 in
468   iter_blocks ntfs file (
469     fun lcn vcn data ->
470       for i = 0 to String.length data - 1 do
471         let c = Char.code data.[i] in
472         if c = 0 then                   (* common cases *)
473           free := !free +^ ~^8
474         else if c = 0xff then
475           used := !used +^ ~^8
476         else (                          (* uncommon case: count the bits *)
477           let m = ref 0x80 in
478           while !m > 0 do
479             if c land !m <> 0 then
480               used := !used +^ ~^1
481             else
482               free := !free +^ ~^1;
483             m := !m lsr 1
484           done
485         )
486       done
487   );
488   (!used, !free)
489
490 and find_system_file { ntfs_mft_records = mft_records } fname =
491   let rec loop =
492     function 
493     | [] -> raise Not_found
494     | ({ ntfs_filename = Some { ntfs_name = name } } as file) :: _
495         when name = fname ->
496         file
497     | _ :: rest -> loop rest
498   in
499   loop mft_records
500
501 and iter_blocks { ntfs_blocksize = blocksize; ntfs_dev = dev }
502     { ntfs_data = data } f =
503   match data with
504   | None -> ()                          (* No $Data attribute. *)
505   | Some { ntfs_data_size = data_size; ntfs_runlist = runlist } ->
506       let rec loop data_size = function
507         | [] -> ()
508
509         (* Run of vcnsize clusters. *)
510         | ((vcnstart, vcnsize), Some lcn) :: rest ->
511             let data_size = ref data_size in
512             let lcn = ref lcn in
513             let vcn = ref vcnstart in
514             let vcnsize = ref vcnsize in
515             while !vcnsize > ~^0 && !data_size > ~^0 do
516               let size = min blocksize !data_size in
517               let data = dev#read (!lcn *^ blocksize) size in
518               f (Some !lcn) !vcn data;
519               lcn := !lcn +^ ~^1;
520               vcn := !vcn +^ ~^1;
521               vcnsize := !vcnsize -^ ~^1;
522               data_size := !data_size -^ size
523             done;
524             loop !data_size rest
525
526         (* Sparse hole. *)
527         | ((vcnstart, vcnsize), None) :: rest ->
528             let data_size = ref data_size in
529             let vcn = ref vcnstart in
530             let vcnsize = ref vcnsize in
531             while !vcnsize > ~^0 && !data_size > ~^0 do
532               let size = min blocksize !data_size in
533               let data = String.make size '\000' in
534               f None !vcn data;
535               vcn := !vcn +^ ~^1;
536               vcnsize := !vcnsize -^ ~^1;
537               data_size := !data_size -^ size
538             done;
539             loop !data_size rest
540       in
541       loop data_size runlist
542
543 (* This is a bit limited at the moment because it can only read from
544  * a contiguous part of the file.  System files are usually contiguous
545  * so this is OK for us.
546  *)
547 and read_file { ntfs_blocksize = blocksize; ntfs_dev = dev }
548     { ntfs_data = data } offset size =
549   match data with
550   | None -> raise Not_found             (* No $Data attribute. *)
551   | Some { ntfs_data_size = data_size; ntfs_runlist = runlist } ->
552       if offset < ~^0 || size < ~^0 || offset +^ size >= data_size then
553         invalid_arg "ntfs: read_file: tried to read outside file";
554
555       (* Get the first and last VCNs containing the data. *)
556       let vcn = offset /^ blocksize in
557       let vcnoffset = offset %^ blocksize in
558       let vcnend = (offset +^ size -^ ~^1) /^ blocksize in
559
560       (* Find the run containing this VCN. *)
561       let rec find = function
562         | [] -> raise Not_found
563         | ((vcnstart, vcnsize), lcn) :: _
564             when vcnstart <= vcn && vcn < vcnstart +^ vcnsize &&
565               vcnstart <= vcnend && vcnend < vcnstart +^ vcnsize ->
566             lcn
567         | _ :: rest -> find rest
568       in
569       let lcn = find runlist in
570
571       (* Read the LCNs. *)
572       let data =
573         match lcn with
574         | Some lcn -> dev#read (lcn *^ blocksize +^ vcnoffset) size
575         | None -> String.make size '\000' (* sparse hole *) in
576       data
577
578 (* This is easy: just look at the bitmap. *)
579 and offset_is_free fs offset =
580   try
581     let ntfs = get_private_data fs in
582     let blocksize = ntfs.ntfs_blocksize in
583
584     (* Get the $Bitmap file. *)
585     let file = find_system_file ntfs "$Bitmap" in
586
587     let lcn = offset /^ blocksize in
588
589     (* Read the byte in the bitmap corresponding to this LCN. *)
590     let byteoffset = lcn >^> 3 and bitoffset = lcn &^ ~^7 in
591     let byte = read_file ntfs file byteoffset ~^1 in
592     let byte = Char.code byte.[0] in
593     let bit = byte >^> (~^0x80 >^> (Int63.to_int bitoffset)) in
594
595     bit <> ~^0
596   with
597     Not_found -> false                  (* play it safe *)
598
599 and callbacks =
600   let i = ref 0 in
601   fun () -> {
602     fs_cb_uq = (incr i; !i);
603     fs_cb_name = id;
604     fs_cb_printable_name = "Windows NTFS";
605     fs_cb_offset_is_free = offset_is_free;
606   }
607
608 (* Register the plugin. *)
609 let () = register_plugin ~filesystem:probe id