]> matita.cs.unibo.it Git - helm.git/blob - helm/DEVEL/ocaml-http/http_parser.ml
- implemented heal_header that sanity checks an header
[helm.git] / helm / DEVEL / ocaml-http / http_parser.ml
1
2 (*
3   OCaml HTTP - do it yourself (fully OCaml) HTTP daemon
4
5   Copyright (C) <2002> Stefano Zacchiroli <zack@cs.unibo.it>
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 *)
21
22 open Neturl;;
23 open Printf;;
24
25 open Http_types;;
26 open Http_constants;;
27
28 (*
29 type url_syntax_option =
30     Url_part_not_recognized
31   | Url_part_allowed
32   | Url_part_required
33
34 * (1) scheme://user:password@host:port/path;params?query#fragment
35 *)
36
37 let request_uri_syntax = {
38   url_enable_scheme    = Url_part_not_recognized;
39   url_enable_user      = Url_part_not_recognized;
40   url_enable_password  = Url_part_not_recognized;
41   url_enable_host      = Url_part_not_recognized;
42   url_enable_port      = Url_part_not_recognized;
43   url_enable_path      = Url_part_required;
44   url_enable_param     = Url_part_not_recognized;
45   url_enable_query     = Url_part_allowed;
46   url_enable_fragment  = Url_part_not_recognized;
47   url_enable_other     = Url_part_not_recognized;
48   url_accepts_8bits    = false;
49   url_is_valid         = (fun _ -> true);
50 }
51
52 module CharSet = Set.Make (Char)
53
54   (** create an "is in" predicate over a character set using an efficient,
55   set-based implementation *)
56 let mk_char_predicate chars =
57   let charset =
58     List.fold_left (fun oldset c -> CharSet.add c oldset) CharSet.empty chars
59   in
60   fun c -> CharSet.mem c charset
61
62 let is_http_separator =
63   mk_char_predicate
64     [ '('; ')'; '<'; '>'; '@'; ','; ';'; ':'; '\\'; '"'; '/'; '['; ']'; '?';
65     '='; '{'; '}'; ' '; '\t' ]
66
67 let is_http_ctl c =
68   match Char.code c with
69   | c when (((c >= 0) && (c <= 31)) || (c = 127)) -> true
70   | _ -> false
71
72   (* internal: used to implement is_* functions *)
73 exception Invalid_char;;
74
75 let is_http_token s =
76   try
77     String.iter
78       (fun c ->
79         if (is_http_ctl c) || (is_http_separator) c then raise Invalid_char)
80       s;
81     true
82   with Invalid_char -> false
83
84 let rec is_http_lws s =
85   (match s.[0] with
86   | ' ' | '\t' -> true
87   | '\r' ->
88       (try
89         (s.[1] = '\n') && ((s.[2] = ' ') || (s.[2] = '\t'))
90       with Invalid_argument "String.get" -> false)
91   | _ -> false)
92
93 let is_http_field_name = is_http_token
94
95 let is_http_field_value s =
96   let rec strip_quoted_string = function
97     | [] -> (false, [])
98     | '"' :: tl -> (true, tl)
99     | '\\' :: '"' :: tl -> strip_quoted_string tl
100     | hd :: tl -> strip_quoted_string tl
101   in
102   let rec is_http_field_value' = function
103     | '\r' :: '\n' :: sp :: rest when (sp = ' ' || sp = '\t') -> (* strip LWS *)
104         is_http_field_value' rest
105     | c :: rest when (is_http_ctl c && c <> '\t') ->  (* \t is in CTL /\ SEP *)
106         false (* CTL aren't allowed *)
107     | '"' :: rest ->
108         let (valid, rest) = strip_quoted_string rest in
109         if not valid then false else is_http_field_value' rest
110     | c :: rest -> is_http_field_value' rest
111     | [] -> true
112   in is_http_field_value' (Http_misc.string_explode s)
113
114 let heal_header (name, value) =
115   if not (is_http_field_name name && is_http_field_value value) then
116     raise (Invalid_header (name ^ ": " ^ value))
117   else
118     ()
119
120   (** given an HTTP like query string (e.g. "name1=value1&name2=value2&...")
121   @return a list of pairs [("name1", "value1"); ("name2", "value2")]
122   @raise Malformed_query if the string isn't a valid query string
123   @raise Malformed_query_part if some piece of the query isn't valid
124   *)
125 let split_query_params =
126   let (bindings_sep, binding_sep) = (Pcre.regexp "&", Pcre.regexp "=") in
127   let http_decode url = Netencoding.Url.decode ~plus:false url in
128   fun ~query ->
129     let bindings = Pcre.split ~rex:bindings_sep query in
130     if List.length bindings < 1 then
131       raise (Malformed_query query);
132     List.map
133       (fun binding ->
134         match Pcre.split ~rex:binding_sep binding with
135         | [""; b] -> (* '=b' *) raise (Malformed_query_part (binding, query))
136         | [a; b]  -> (* 'a=b' *) (http_decode a, http_decode b)
137         | [a]     -> (* 'a=' || 'a' *) (http_decode a, "")
138         | _ -> raise (Malformed_query_part (binding, query)))
139       bindings
140
141   (** given an input channel and a separator
142   @return a line read from it (like Pervasives.input_line)
143   line is returned only after reading a separator string; separator string isn't
144   included in the returned value
145   FIXME what about efficiency?, input is performed char-by-char
146   *)
147 let generic_input_line ~sep ~ic =
148   let sep_len = String.length sep in
149   if sep_len < 1 then
150     failwith ("Separator '" ^ sep ^ "' is too short!")
151   else  (* valid separator *)
152     let line = ref "" in
153     let sep_pointer = ref 0 in
154     try
155       while true do
156         if !sep_pointer >= String.length sep then (* line completed *)
157           raise End_of_file
158         else begin (* incomplete line: need to read more *)
159           let ch = input_char ic in
160           if ch = String.get sep !sep_pointer then  (* next piece of sep *)
161             incr sep_pointer
162           else begin  (* useful char *)
163             for i = 0 to !sep_pointer - 1 do
164               line := !line ^ (String.make 1 (String.get sep i))
165             done;
166             sep_pointer := 0;
167             line := !line ^ (String.make 1 ch)
168           end
169         end
170       done;
171       assert false  (* unreacheable statement *)
172     with End_of_file ->
173       if !line = "" then
174         raise End_of_file
175       else
176         !line
177
178   (** given an input channel, reads from it a GET HTTP request and
179   @return a pair <path, query_params> where path is a string representing the
180   requested path and query_params is a list of pairs <name, value> (the GET
181   parameters)
182   *)
183 let parse_request =
184   let patch_empty_path s = (if s = "" then "/" else s) in
185   let pieces_sep = Pcre.regexp " " in
186   fun ic ->
187     let request_line = generic_input_line ~sep:crlf ~ic in
188     match Pcre.split ~rex:pieces_sep request_line with
189     | [meth; request_uri_raw; http_version] ->
190         if meth <> "GET" then
191           raise (Unsupported_method meth);
192         (match http_version with
193         | "HTTP/1.0" | "HTTP/1.1" -> ()
194         | _ -> raise (Unsupported_HTTP_version http_version));
195         let request_uri =
196           try
197             url_of_string request_uri_syntax request_uri_raw
198           with Malformed_URL ->
199             raise (Malformed_request_URI request_uri_raw)
200         in
201         let path =
202           patch_empty_path (String.concat "/" (url_path request_uri))
203         in
204         let query_params =
205           try (* act on HTTP encoded URIs *)
206             split_query_params (url_query ~encoded:true request_uri)
207           with Not_found -> []
208         in
209         Http_common.debug_print
210           (sprintf
211             "recevied request; path: %s; params: %s"
212             path
213             (String.concat
214               ", "
215               (List.map (fun (n, v) -> n ^ "=" ^ v) query_params)));
216         (path, query_params)
217     | _ -> raise (Malformed_request request_line)
218