Updated MANIFEST.
[ocaml-bitstring.git] / bitmatch.mli
1 (** Bitmatch library. *)
2 (* Copyright (C) 2008 Red Hat Inc., Richard W.M. Jones
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *
18  * $Id: bitmatch.mli,v 1.10 2008-04-02 12:29:03 rjones Exp $
19  *)
20
21 (**
22    {{:#reference}Jump straight to the reference section for
23    documentation on types and functions}.
24
25    {2 Introduction}
26
27    Bitmatch adds Erlang-style bitstrings and matching over bitstrings
28    as a syntax extension and library for OCaml.  You can use
29    this module to both parse and generate binary formats.
30
31    {{:http://et.redhat.com/~rjones/bitmatch/}OCaml bitmatch website}
32
33    {2 Examples}
34
35    A function which can parse IPv4 packets:
36
37 {[
38 let display pkt =
39   bitmatch pkt with
40   (* IPv4 packet header
41     0                   1                   2                   3   
42     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
43    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
44    |   4   |  IHL  |Type of Service|          Total Length         |
45    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
46    |         Identification        |Flags|      Fragment Offset    |
47    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
48    |  Time to Live |    Protocol   |         Header Checksum       |
49    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50    |                       Source Address                          |
51    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52    |                    Destination Address                        |
53    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
54    |                    Options                    |    Padding    |
55    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
56   *)
57   | 4 : 4; hdrlen : 4; tos : 8;   length : 16;
58     identification : 16;          flags : 3; fragoffset : 13;
59     ttl : 8; protocol : 8;        checksum : 16;
60     source : 32;
61     dest : 32;
62     options : (hdrlen-5)*32 : bitstring;
63     payload : -1 : bitstring ->
64
65     printf "IPv4:\n";
66     printf "  header length: %d * 32 bit words\n" hdrlen;
67     printf "  type of service: %d\n" tos;
68     printf "  packet length: %d bytes\n" length;
69     printf "  identification: %d\n" identification;
70     printf "  flags: %d\n" flags;
71     printf "  fragment offset: %d\n" fragoffset;
72     printf "  ttl: %d\n" ttl;
73     printf "  protocol: %d\n" protocol;
74     printf "  checksum: %d\n" checksum;
75     printf "  source: %lx  dest: %lx\n" source dest;
76     printf "  header options + padding:\n";
77     Bitmatch.hexdump_bitstring stdout options;
78     printf "  packet payload:\n";
79     Bitmatch.hexdump_bitstring stdout payload
80
81   | version : 4 ->
82     eprintf "unknown IP version %d\n" version;
83     exit 1
84
85   | _ as pkt ->
86     eprintf "data is smaller than one nibble:\n";
87     Bitmatch.hexdump_bitstring stderr pkt;
88     exit 1
89 ]}
90
91    A program which can parse
92    {{:http://lxr.linux.no/linux/include/linux/ext3_fs.h}Linux EXT3 filesystem superblocks}:
93
94 {[
95 let bits = Bitmatch.bitstring_of_file "tests/ext3_sb"
96
97 let () =
98   bitmatch bits with
99   | s_inodes_count : 32 : littleendian;       (* Inodes count *)
100     s_blocks_count : 32 : littleendian;       (* Blocks count *)
101     s_r_blocks_count : 32 : littleendian;     (* Reserved blocks count *)
102     s_free_blocks_count : 32 : littleendian;  (* Free blocks count *)
103     s_free_inodes_count : 32 : littleendian;  (* Free inodes count *)
104     s_first_data_block : 32 : littleendian;   (* First Data Block *)
105     s_log_block_size : 32 : littleendian;     (* Block size *)
106     s_log_frag_size : 32 : littleendian;      (* Fragment size *)
107     s_blocks_per_group : 32 : littleendian;   (* # Blocks per group *)
108     s_frags_per_group : 32 : littleendian;    (* # Fragments per group *)
109     s_inodes_per_group : 32 : littleendian;   (* # Inodes per group *)
110     s_mtime : 32 : littleendian;              (* Mount time *)
111     s_wtime : 32 : littleendian;              (* Write time *)
112     s_mnt_count : 16 : littleendian;          (* Mount count *)
113     s_max_mnt_count : 16 : littleendian;      (* Maximal mount count *)
114     0xef53 : 16 : littleendian ->             (* Magic signature *)
115
116     printf "ext3 superblock:\n";
117     printf "  s_inodes_count = %ld\n" s_inodes_count;
118     printf "  s_blocks_count = %ld\n" s_blocks_count;
119     printf "  s_free_inodes_count = %ld\n" s_free_inodes_count;
120     printf "  s_free_blocks_count = %ld\n" s_free_blocks_count
121
122   | _ ->
123     eprintf "not an ext3 superblock!\n%!";
124     exit 2
125 ]}
126
127    Constructing packets for a simple binary message
128    protocol:
129
130 {[
131 (*
132   +---------------+---------------+--------------------------+
133   | type          | subtype       | parameter                |
134   +---------------+---------------+--------------------------+
135    <-- 16 bits --> <-- 16 bits --> <------- 32 bits -------->
136
137   All fields are in network byte order.
138 *)
139
140 let make_message typ subtype param =
141   (BITSTRING
142      typ : 16;
143      subtype : 16;
144      param : 32) ;;
145 ]}
146
147    {2 Loading, creating bitstrings}
148
149    The basic data type is the {!bitstring}, a string of bits of
150    arbitrary length.  Bitstrings can be any length in bits and
151    operations do not need to be byte-aligned (although they will
152    generally be more efficient if they are byte-aligned).
153
154    Internally a bitstring is stored as a normal OCaml [string]
155    together with an offset and length, where the offset and length are
156    measured in bits.  Thus one can efficiently form substrings of
157    bitstrings, overlay a bitstring on existing data, and load and save
158    bitstrings from files or other external sources.
159
160    To load a bitstring from a file use {!bitstring_of_file} or
161    {!bitstring_of_chan}.
162
163    There are also functions to create bitstrings from arbitrary data.
164    See the {{:#reference}reference} below.
165
166    {2 Matching bitstrings with patterns}
167
168    Use the [bitmatch] operator (part of the syntax extension) to break
169    apart a bitstring into its fields.  [bitmatch] works a lot like the
170    OCaml [match] operator.
171
172    The general form of [bitmatch] is:
173
174    [bitmatch] {i bitstring-expression} [with]
175
176    [|] {i pattern} [->] {i code}
177
178    [|] {i pattern} [->] {i code}
179
180    [|] ...
181
182    As with normal match, the statement attempts to match the
183    bitstring against each pattern in turn.  If none of the patterns
184    match then the standard library [Match_failure] exception is
185    thrown.
186
187    Patterns look a bit different from normal match patterns.  The
188    consist of a list of bitfields separated by [;] where each bitfield
189    contains a bind variable, the width (in bits) of the field, and
190    other information.  Some example patterns:
191
192 {[
193 bitmatch bits with
194
195 | version : 8; name : 8; param : 8 -> ...
196
197    (* Bitstring of at least 3 bytes.  First byte is the version
198       number, second byte is a field called name, third byte is
199       a field called parameter. *)
200
201 | flag : 1 ->
202    printf "flag is %b\n" flag
203
204    (* A single flag bit (mapped into an OCaml boolean). *)
205
206 | len : 4; data : 1+len ->
207    printf "len = %d, data = 0x%Lx\n" len data
208
209    (* A 4-bit length, followed by 1-16 bits of data, where the
210       length of the data is computed from len. *)
211
212 | ipv6_source : 128 : bitstring;
213   ipv6_dest : 128 : bitstring -> ...
214
215    (* IPv6 source and destination addresses.  Each is 128 bits
216       and is mapped into a bitstring type which will be a substring
217       of the main bitstring expression. *)
218 ]}
219
220    You can also add conditional when-clauses:
221
222 {[
223 | version : 4
224     when version = 4 || version = 6 -> ...
225
226    (* Only match and run the code when version is 4 or 6.  If
227       it isn't we will drop through to the next case. *)
228 ]}
229
230    Note that the pattern is only compared against the first part of
231    the bitstring (there may be more data in the bitstring following
232    the pattern, which is not matched).  In terms of regular
233    expressions you might say that the pattern matches [^pattern], not
234    [^pattern$].  To ensure that the bitstring contains only the
235    pattern, add a length -1 bitstring to the end and test that its
236    length is zero in the when-clause:
237
238 {[
239 | n : 4;
240   rest : -1 : bitstring
241     when Bitmatch.bitstring_length rest = 0 -> ...
242
243    (* Only matches exactly 4 bits. *)
244 ]}
245
246    Normally the first part of each field is a binding variable,
247    but you can also match a constant, as in:
248
249 {[
250 | 6 : 4 -> ...
251
252    (* Only matches if the first 4 bits contain the integer 6. *)
253 ]}
254
255    {3:patternfieldreference Pattern field reference}
256
257    The exact format of each pattern field is:
258
259    [pattern : length [: qualifier [,qualifier ...]]]
260
261    [pattern] is the pattern, binding variable name, or constant to
262    match.  [length] is the length in bits which may be either a
263    constant or an expression.  The length expression is just an OCaml
264    expression and can use any values defined in the program, and refer
265    back to earlier fields (but not to later fields).
266
267    Integers can only have lengths in the range \[1..64\] bits.  See the
268    {{:#integertypes}integer types} section below for how these are
269    mapped to the OCaml int/int32/int64 types.  This is checked
270    at compile time if the length expression is constant, otherwise it is
271    checked at runtime and you will get a runtime exception eg. in
272    the case of a computed length expression.
273
274    A bitstring field of length -1 matches all the rest of the
275    bitstring (thus this is only useful as the last field in a
276    pattern).
277
278    A bitstring field of length 0 matches an empty bitstring
279    (occasionally useful when matching optional subfields).
280
281    Qualifiers are a list of identifiers which control the type,
282    signedness and endianness of the field.  Permissible qualifiers are:
283
284    - [int] (field has an integer type)
285    - [bitstring] (field is a bitstring type)
286    - [signed] (field is signed)
287    - [unsigned] (field is unsigned)
288    - [bigendian] (field is big endian - a.k.a network byte order)
289    - [littleendian] (field is little endian - a.k.a Intel byte order)
290    - [nativeendian] (field is same endianness as the machine)
291
292    The default settings are [int], [unsigned], [bigendian].
293
294    Note that many of these qualifiers cannot be used together,
295    eg. bitstrings do not have endianness.  The syntax extension should
296    give you a compile-time error if you use incompatible qualifiers.
297
298    {3 Other cases in bitmatch}
299
300    As well as a list of fields, it is possible to name the
301    bitstring and/or have a default match case:
302
303 {[
304 | _ -> ...
305
306    (* Default match case. *)
307
308 | _ as pkt -> ...
309
310    (* Default match case, with 'pkt' bound to the whole bitstring. *)
311 ]}
312
313    {2 Constructing bitstrings}
314
315    Bitstrings may be constructed using the [BITSTRING] operator (as an
316    expression).  The [BITSTRING] operator takes a list of fields,
317    similar to the list of fields for matching:
318
319 {[
320 let version = 1 ;;
321 let data = 10 ;;
322 let bits =
323   BITSTRING
324     version : 4;
325     data : 12 ;;
326
327    (* Constructs a 16-bit bitstring with the first four bits containing
328       the integer 1, and the following 12 bits containing the integer 10,
329       arranged in network byte order. *)
330
331 Bitmatch.hexdump_bitstring stdout bits ;;
332
333    (* Prints:
334
335       00000000  10 0a         |..              |
336     *)
337 ]}
338
339    The format of each field is the same as for pattern fields (see
340    {{:#patternfieldreference}Pattern field reference section}), and
341    things like computed length fields, fixed value fields, insertion
342    of bitstrings within bitstrings, etc. are all supported.
343
344    {3 Construction exception}
345
346    The [BITSTRING] operator may throw a {!Construct_failure}
347    exception at runtime.
348
349    Runtime errors include:
350
351    - int field length not in the range \[1..64\]
352    - a bitstring with a length declared which doesn't have the
353      same length at runtime
354    - trying to insert an out of range value into an int field
355      (eg. an unsigned int field which is 2 bits wide can only
356      take values in the range \[0..3\]).
357
358    {2:integertypes Integer types}
359
360    Integer types are mapped to OCaml types [bool], [int], [int32] or
361    [int64] using a system which tries to ensure that (a) the types are
362    reasonably predictable and (b) the most efficient type is
363    preferred.
364
365    The rules are slightly different depending on whether the bit
366    length expression in the field is a compile-time constant or a
367    computed expression.
368
369    Detection of compile-time constants is quite simplistic so only an
370    immediate, simple integer is recognised as a constant and anything
371    else is considered a computed expression, even expressions such as
372    [5-2] which are obviously (to our eyes) constant.
373
374    In any case the bit size of an integer is limited to the range
375    \[1..64\].  This is detected as a compile-time error if that is
376    possible, otherwise a runtime check is added which can throw an
377    [Invalid_argument] exception.
378
379    The mapping is thus:
380
381    {v
382    Bit size         ---- OCaml type ----
383                 Constant        Computed expression
384
385    1            bool            int64
386    2..31        int             int64
387    32           int32           int64
388    33..64       int64           int64
389    v}
390
391    A possible future extension may allow people with 64 bit computers
392    to specify a more optimal [int] type for bit sizes in the range
393    [32..63].  If this was implemented then such code {i could not even
394    be compiled} on 32 bit platforms, so it would limit portability.
395
396    Another future extension may be to allow computed
397    expressions to assert min/max range for the bit size,
398    allowing a more efficient data type than int64 to be
399    used.  (Of course under such circumstances there would
400    still need to be a runtime check to enforce the
401    size).
402
403    {2 Compiling}
404
405    Using the compiler directly you can do:
406
407    {v
408    ocamlc -I bitmatch -pp "camlp4o -I bitmatch pa_bitmatch.cmo" foo.ml -o foo
409    v}
410
411    Using findlib:
412
413    {v
414    ocamlfind ocamlc -package bitmatch.syntax -linkpkg foo.ml -o foo
415    v}
416
417    {2 Security and type safety}
418
419    {3 Security on input}
420
421    The main concerns for input are buffer overflows and denial
422    of service.
423
424    It is believed that this library is robust against attempted buffer
425    overflows.  In addition to OCaml's normal bounds checks, we check
426    that field lengths are >= 0, and many additional checks.
427
428    Denial of service attacks are more problematic although we still
429    believe that the library is robust.  We only work forwards through
430    the bitstring, thus computation will eventually terminate.  As for
431    computed lengths, code such as this is thought to be secure:
432
433 {[
434 bitmatch bits with
435 | len : 64;
436   buffer : Int64.to_int len : bitstring ->
437 ]}
438
439    The [len] field can be set arbitrarily large by an attacker, but
440    when pattern-matching against the [buffer] field this merely causes
441    a test such as [if len <= remaining_size] to fail.  Even if the
442    length is chosen so that [buffer] bitstring is allocated, the
443    allocation of sub-bitstrings is efficient and doesn't involve an
444    arbitary-sized allocation or any copying.
445
446    The main protection against attackers should therefore be to ensure
447    that the main program will only read input bitstrings up to a
448    certain length, which is outside the scope of this library.
449
450    {3 Security on output}
451
452    As with the input side, computed lengths are believed to be
453    safe.  For example:
454
455 {[
456 let len = read_untrusted_source () in
457 let buffer = allocate_bitstring () in
458 BITSTRING
459   buffer : len : bitstring
460 ]}
461
462    This code merely causes a check that buffer's length is the same as
463    [len].  However the program function [allocate_bitstring] must
464    refuse to allocate an oversized buffer (but that is outside the
465    scope of this library).
466
467    {3 Order of evaluation}
468
469    In [bitmatch] statements, fields are evaluated left to right.
470
471    Note that the when-clause is evaluated {i last}, so if you are
472    relying on the when-clause to filter cases then your code may do a
473    lot of extra and unncessary pattern-matching work on fields which
474    may never be needed just to evaluate the when-clause.  You can
475    usually rearrange the code to do only the first part of the match,
476    followed by the when-clause, followed by a second inner bitmatch.
477
478    {3 Safety}
479
480    The current implementation is believed to be fully type-safe,
481    and makes compile and run-time checks where appropriate.  If
482    you find a case where a check is missing please submit a
483    bug report or a patch.
484
485    {2 Limits}
486
487    These are thought to be the current limits:
488
489    Integers: \[1..64\] bits.
490
491    Bitstrings (32 bit platforms): maximum length is limited
492    by the string size, ie. 16 MBytes.
493
494    Bitstrings (64 bit platforms): maximum length is thought to be
495    limited by the string size, ie. effectively unlimited.
496
497    Bitstrings must be loaded into memory before we can match against
498    them.  Thus available memory may be considered a limit for some
499    applications.
500
501    {2:reference Reference}
502    {3 Types}
503 *)
504
505 type bitstring = string * int * int
506 (** [bitstring] is the basic type used to store bitstrings.
507
508     The type contains the underlying data (a string),
509     the current bit offset within the string and the
510     current bit length of the string (counting from the
511     bit offset).  Note that the offsets are bits, not bytes.
512
513     Normally you don't need to use the bitstring type
514     directly, since there are functions and syntax
515     extensions which hide the details.
516     See {!bitstring_of_file}, {!hexdump_bitstring},
517     {!bitstring_length}.
518 *)
519
520 (** {3 Exceptions} *)
521
522 exception Construct_failure of string * string * int * int
523 (** [Construct_failure (message, file, line, char)] may be
524     raised by the [BITSTRING] constructor.
525
526     Common reasons are that values are out of range of
527     the fields that contain them, or that computed lengths
528     are impossible (eg. negative length bitfields).
529
530     [message] is the error message.
531
532     [file], [line] and [char] point to the original source
533     location of the [BITSTRING] constructor that failed.
534 *)
535
536 (** {3 Bitstrings} *)
537
538 val empty_bitstring : bitstring
539 (** [empty_bitstring] is the empty, zero-length bitstring. *)
540
541 val create_bitstring : int -> bitstring
542 (** [create_bitstring n] creates an [n] bit bitstring
543     containing all zeroes. *)
544
545 val make_bitstring : int -> char -> bitstring
546 (** [make_bitstring n c] creates an [n] bit bitstring
547     containing the repeated 8 bit pattern in [c].
548
549     For example, [make_bitstring 16 '\x5a'] will create
550     the bitstring [0x5a5a] or in binary [0101 1010 0101 1010].
551
552     Note that the length is in bits, not bytes. *)
553
554 val bitstring_of_chan : in_channel -> bitstring
555 (** [bitstring_of_chan chan] loads the contents of
556     the input channel [chan] as a bitstring.
557
558     The length of the final bitstring is determined
559     by the remaining input in [chan], but will always
560     be a multiple of 8 bits. *)
561
562 val bitstring_of_file : string -> bitstring
563 (** [bitstring_of_file filename] loads the named file
564     into a bitstring. *)
565
566 val hexdump_bitstring : out_channel -> bitstring -> unit
567 (** [hexdump_bitstring chan bitstring] prints the bitstring
568     to the output channel in a format similar to the
569     Unix command [hexdump -C]. *)
570
571 val bitstring_length : bitstring -> int
572 (** [bitstring_length bitstring] returns the length of
573     the bitstring in bits. *)
574
575 (** {3 Bitstring buffer} *)
576
577 module Buffer : sig
578   type t
579   val create : unit -> t
580   val contents : t -> bitstring
581   val add_bits : t -> string -> int -> unit
582   val add_bit : t -> bool -> unit
583   val add_byte : t -> int -> unit
584 end
585 (** Buffers are mainly used by the [BITSTRING] constructor, but
586     may also be useful for end users.  They work much like the
587     standard library [Buffer] module. *)
588
589 (** {3 Miscellaneous} *)
590
591 val debug : bool ref
592 (** Set this variable to true to enable extended debugging.
593     This only works if debugging was also enabled in the
594     [pa_bitmatch.ml] file at compile time, otherwise it
595     does nothing. *)
596
597 (**/**)
598
599 (* Private functions, called from generated code.  Do not use
600  * these directly - they are not safe.
601  *)
602
603 val extract_bitstring : string -> int -> int -> int -> bitstring * int * int
604
605 val extract_remainder : string -> int -> int -> bitstring * int * int
606
607 val extract_bit : string -> int -> int -> int -> bool * int * int
608
609 val extract_char_unsigned : string -> int -> int -> int -> int * int * int
610
611 val extract_int_be_unsigned : string -> int -> int -> int -> int * int * int
612
613 val extract_int_le_unsigned : string -> int -> int -> int -> int * int * int
614
615 val extract_int32_be_unsigned : string -> int -> int -> int -> int32 * int * int
616
617 val extract_int32_le_unsigned : string -> int -> int -> int -> int32 * int * int
618
619 val extract_int64_be_unsigned : string -> int -> int -> int -> int64 * int * int
620
621 val construct_bit : Buffer.t -> bool -> int -> unit
622
623 val construct_char_unsigned : Buffer.t -> int -> int -> exn -> unit
624
625 val construct_int_be_unsigned : Buffer.t -> int -> int -> exn -> unit
626
627 val construct_int64_be_unsigned : Buffer.t -> int64 -> int -> exn -> unit