]> matita.cs.unibo.it Git - helm.git/blob - helm/DEVEL/ocaml-http/daemon.ml
added ocaml-http 0.0.1
[helm.git] / helm / DEVEL / ocaml-http / daemon.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 let debug = false
26 let debug_print str =
27   prerr_endline ("DEBUG: " ^ str);
28   flush stderr
29
30 let default_addr = "0.0.0.0"
31 let default_port = 80
32 let default_timeout = 300
33
34 (*
35 type url_syntax_option =
36     Url_part_not_recognized
37   | Url_part_allowed
38   | Url_part_required
39
40 * (1) scheme://user:password@host:port/path;params?query#fragment
41 *)
42
43 let request_uri_syntax = {
44   url_enable_scheme    = Url_part_not_recognized;
45   url_enable_user      = Url_part_not_recognized;
46   url_enable_password  = Url_part_not_recognized;
47   url_enable_host      = Url_part_not_recognized;
48   url_enable_port      = Url_part_not_recognized;
49   url_enable_path      = Url_part_required;
50   url_enable_param     = Url_part_not_recognized;
51   url_enable_query     = Url_part_allowed;
52   url_enable_fragment  = Url_part_not_recognized;
53   url_enable_other     = Url_part_not_recognized;
54   url_accepts_8bits    = false;
55   url_is_valid         = (fun _ -> true);
56 }
57
58 let crlf = "\r\n"
59
60 exception Malformed_request of string
61 exception Unsupported_method of string
62 exception Malformed_request_URI of string
63 exception Unsupported_HTTP_version of string
64 exception Malformed_query of string
65 exception Malformed_query_binding of string * string
66
67   (** given a list of length 2
68   @return a pair formed by the elements of the list
69   @raise Assert_failure if the list length isn't 2
70   *)
71 let pair_of_2_sized_list = function
72   | [a;b] -> (a,b)
73   | _ -> assert false
74
75   (** given an HTTP like query string (e.g. "name1=value1&name2=value2&...")
76   @return a list of pairs [("name1", "value1"); ("name2", "value2")]
77   @raise Malformed_query if the string isn't a valid query string
78   @raise Malformed_query_binding if some piece of the query isn't valid
79   *)
80 let split_query_params =
81   let (bindings_sep, binding_sep) = (Pcre.regexp "&", Pcre.regexp "=") in
82   fun ~query ->
83     let bindings = Pcre.split ~rex:bindings_sep query in
84     if List.length bindings < 1 then
85       raise (Malformed_query query);
86     List.map
87       (fun binding ->
88         let pieces = Pcre.split ~rex:binding_sep binding in
89         if List.length pieces <> 2 then
90           raise (Malformed_query_binding (binding, query));
91         pair_of_2_sized_list pieces)
92       bindings
93
94   (** given an input channel and a separator
95   @return a line read from it (like Pervasives.input_line)
96   line is returned only after reading a separator string; separator string isn't
97   included in the returned value
98   FIXME what about efficiency?, input is performed char-by-char
99   *)
100 let generic_input_line ~sep ~ic =
101   let sep_len = String.length sep in
102   if sep_len < 1 then
103     failwith ("Separator '" ^ sep ^ "' is too short!")
104   else  (* valid separator *)
105     let line = ref "" in
106     let sep_pointer = ref 0 in
107     try
108       while true do
109         if !sep_pointer >= String.length sep then (* line completed *)
110           raise End_of_file
111         else begin (* incomplete line: need to read more *)
112           let ch = input_char ic in
113           if ch = String.get sep !sep_pointer then  (* next piece of sep *)
114             incr sep_pointer
115           else begin  (* useful char *)
116             for i = 0 to !sep_pointer - 1 do
117               line := !line ^ (String.make 1 (String.get sep i))
118             done;
119             sep_pointer := 0;
120             line := !line ^ (String.make 1 ch)
121           end
122         end
123       done;
124       assert false  (* unreacheable statement *)
125     with End_of_file ->
126       if !line = "" then
127         raise End_of_file
128       else
129         !line
130
131   (** given an input channel, reads from it a GET HTTP request and
132   @return a pair <path, query_params> where path is a string representing the
133   requested path and query_params is a list of pairs <name, value> (the GET
134   parameters)
135   *)
136 let parse_http_request =
137   let patch_empty_path s = (if s = "" then "/" else s) in
138   let pieces_sep = Pcre.regexp " " in
139   fun ~ic ->
140     let request_line = generic_input_line ~sep:crlf ~ic in
141     if debug then
142       debug_print ("request_line: '" ^ request_line ^ "'");
143     match Pcre.split ~rex:pieces_sep request_line with
144     | [meth; request_uri_raw; http_version] ->
145         if meth <> "GET" then
146           raise (Unsupported_method meth);
147         (match http_version with
148         | "HTTP/1.0" | "HTTP/1.1" -> ()
149         | _ -> raise (Unsupported_HTTP_version http_version));
150         let request_uri =
151           try
152             url_of_string request_uri_syntax request_uri_raw
153           with Malformed_URL ->
154             raise (Malformed_request_URI request_uri_raw)
155         in
156         let path =
157           patch_empty_path (String.concat "/" (url_path request_uri))
158         in
159         let query_params =
160           try split_query_params (url_query request_uri) with Not_found -> []
161         in
162         (path, query_params)
163     | _ -> raise (Malformed_request request_line)
164
165   (** send raw data on outchan, flushing it afterwards *)
166 let send_raw ~data outchan =
167   output_string outchan data;
168   flush outchan
169
170 let send_CRLF = send_raw ~data:crlf
171
172   (** TODO perform some sanity test on header and value *)
173 let send_header ~header ~value = send_raw ~data:(header ^ ": " ^ value ^ crlf)
174
175 let send_headers ~headers outchan =
176   List.iter (fun (header, value) -> send_header ~header ~value outchan) headers
177
178   (** internal: parse a code argument from a function which have two optional
179   arguments "code" and "status" *)
180 let get_code_argument func_name =
181   fun ~code ~status ->
182     (match code, status with
183     | Some c, None -> c
184     | None, Some s -> Common.code_of_status s
185     | Some _, Some _ ->
186         failwith (func_name ^ " you must give 'code' or 'status', not both")
187     | None, None ->
188         failwith (func_name ^ " you must give 'code' or 'status', not none"))
189
190   (** internal: low level for send_status_line *)
191 let send_status_line' ~version ~code =
192   let status_line =
193     String.concat
194       " "
195       [ Common.string_of_version version;
196       string_of_int code;
197       Common.reason_phrase_of_code code ]
198   in
199   send_raw ~data:(status_line ^ crlf)
200
201 let send_status_line ?(version = Common.http_version) ?code ?status outchan =
202   send_status_line'
203     ~version
204     ~code:(get_code_argument "Daemon.send_status_line" ~code ~status)
205     outchan
206
207 let send_basic_headers ?(version = Common.http_version) ?code ?status outchan =
208   send_status_line'
209     ~version ~code:(get_code_argument "Daemon.send_basic_headers" ~code ~status)
210     outchan;
211   send_headers
212     ~headers:["Date", Misc.date_822 (); "Server", "OCaml HTTP Daemon"]
213     outchan
214
215   (** internal: send a fooish body explaining in HTML form the 'reason phrase'
216   of an HTTP response; body, if given, will be appended to the body *)
217 let send_foo_body ~code ~body =
218   let reason_phrase = Common.reason_phrase_of_code code in
219   let body =
220     sprintf
221 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
222 <HTML><HEAD>
223 <TITLE>%d %s</TITLE>
224 </HEAD><BODY>
225 <H1>%d - %s</H1>%s
226 </BODY></HTML>"
227       code reason_phrase code reason_phrase
228       (match body with None -> "" | Some text -> "\n" ^ text)
229   in
230   send_raw ~data:body
231
232   (** internal: low level for respond_redirect, respond_error, ...
233   This function send a status line corresponding to a given code, some basic
234   headers, the additional headers (if given) and an HTML page containing the
235   reason phrase; if body is given it will be included in the body of the HTML
236   page *)
237 let send_empty_response
238   f_name ?(is_valid_status = fun _ -> true) ?(headers = []) ~body () =
239     fun ?(version = Common.http_version) ?code ?status outchan ->
240       let code = get_code_argument f_name ~code ~status in
241       if not (is_valid_status code) then
242         failwith (sprintf "'%d' isn't a valid status code for %s" code f_name)
243       else begin  (* status code suitable for answering *)
244         send_basic_headers ~version ~code outchan;
245         send_header ~header:"Connection" ~value:"close" outchan;
246         send_header
247           ~header:"Content-Type"
248           ~value:"text/html; charset=iso-8859-1"
249           outchan;
250         send_headers ~headers outchan;
251         send_CRLF outchan;
252         send_foo_body ~code ~body outchan
253       end
254
255   (* TODO sanity tests on location *)
256 let respond_redirect
257   ~location ?body
258   ?(version = Common.http_version) ?(code = 301) ?status outchan =
259     let code = 
260       match status with
261       | None -> code
262       | Some (s: Types.redirection_status) -> Common.code_of_status s
263     in
264     send_empty_response
265       "Daemon.respond_redirect" ~is_valid_status:Common.is_redirection
266       ~headers:["Location", location] ~body ()
267       ~version ~code outchan
268
269 let respond_error
270   ?body
271   ?(version = Common.http_version) ?(code = 400) ?status outchan =
272     let code =
273       match status with
274       | None -> code
275       | Some s -> Common.code_of_status s
276     in
277     send_empty_response
278       "Daemon.respond_error" ~is_valid_status:Common.is_error ~body ()
279       ~version ~code outchan
280
281 let respond_not_found ~url ?(version = Common.http_version) outchan =
282   send_empty_response
283     "Daemon.respond_not_found" ~body:None ()
284     ~version ~code:404 outchan
285
286 let respond_forbidden ~url ?(version = Common.http_version) outchan =
287   send_empty_response
288     "Daemon.respond_permission_denied" ~body:None ()
289     ~version ~code:403 outchan
290
291 let send_file ?name ?file outchan =
292   let buflen = 1024 in
293   let buf = String.make buflen ' ' in
294   let (file, cleanup) =
295     (match (name, file) with
296     | Some n, None -> (* if we open the file, we close it before returning *)
297         let f = open_in n in
298         f, (fun () -> close_in f)
299     | None, Some f -> (f, (fun () -> ()))
300     | _ -> failwith "Daemon.send_file: either name or file must be given")
301   in
302   try
303     while true do
304       let bytes = input file buf 0 buflen in
305       if bytes = 0 then
306         raise End_of_file
307       else
308         output outchan buf 0 bytes
309     done;
310     assert false
311   with End_of_file ->
312     begin
313       flush outchan;
314       cleanup ()
315     end
316
317   (* TODO interface is too ugly to advertise this function in .mli *)
318   (** create a minimal HTML directory listing of a given directory and send it
319   over an out_channel, directory is passed as a dir_handle; name is the
320   directory name, used for pretty printing purposes; path is the opened dir
321   path, used to test its contents with stat *)
322 let send_dir_listing ~dir ~name ~path outchan =
323   fprintf outchan "<html>\n<head><title>%s</title></head>\n<body>\n" name;
324   let (dirs, files) =
325     List.partition (fun e -> Misc.is_directory (path ^ e)) (Misc.ls dir)
326   in
327   List.iter
328     (fun d -> fprintf outchan "<a href=\"%s/\">%s/</a><br />\n" d d)
329     (List.sort compare dirs);
330   List.iter
331     (fun f -> fprintf outchan "<a href=\"%s\">%s</a><br />\n" f f)
332     (List.sort compare files);
333   fprintf outchan "</body>\n</html>";
334   flush outchan
335
336 let respond_file ~fname ?(version = Common.http_version) outchan =
337   (** ASSUMPTION: 'fname' doesn't begin with a "/"; it's relative to the current
338   document root (usually the daemon's cwd) *)
339   let droot = Sys.getcwd () in  (* document root *)
340   let path = droot ^ "/" ^ fname in (* full path to the desired file *)
341   if not (Sys.file_exists path) then (* file not found *)
342     respond_not_found ~url:fname outchan
343   else begin
344     try
345       if Misc.is_directory path then begin (* file found, is a dir *)
346         let dir = Unix.opendir path in
347         send_basic_headers ~version ~code:200 outchan;
348         send_header "Content-Type" "text/html" outchan;
349         send_CRLF outchan;
350         send_dir_listing ~dir ~name:fname ~path outchan;
351         Unix.closedir dir
352       end else begin  (* file found, is something else *)
353         let file = open_in fname in
354         send_basic_headers ~version ~code:200 outchan;
355         send_header
356           ~header:"Content-Length"
357           ~value:(string_of_int (Misc.filesize fname))
358           outchan;
359         send_CRLF outchan;
360         send_file ~file outchan;
361         close_in file
362       end
363     with
364     | Unix.Unix_error (Unix.EACCES, s, _) when (s = fname) ->
365         respond_forbidden ~url:fname ~version outchan
366     | Sys_error s when
367         (Pcre.pmatch ~rex:(Pcre.regexp (fname ^ ": Permission denied")) s) ->
368           respond_forbidden ~url:fname ~version outchan
369   end
370
371 let respond_with (res: Types.response) outchan =
372   res#serialize outchan;
373   flush outchan
374
375 let start
376   ?(addr = default_addr) ?(port = default_port)
377   ?(timeout = Some default_timeout)
378   callback
379   =
380   let sockaddr = Unix.ADDR_INET (Unix.inet_addr_of_string addr, port) in
381   let timeout_callback signo =
382     if signo = Sys.sigalrm then begin
383       debug_print "TIMEOUT, exiting ...";
384       exit 2
385     end
386   in
387   let daemon_callback inchan outchan =
388     (match timeout with
389     | Some timeout ->
390         ignore (Sys.signal Sys.sigalrm (Sys.Signal_handle timeout_callback));
391         ignore (Unix.alarm timeout)
392     | None -> ());
393     try
394       let (path, parameters) = parse_http_request inchan in
395       callback path parameters outchan;
396       flush outchan
397     with
398     | End_of_file ->
399         respond_error ~code:400 ~body:"Unexpected End Of File" outchan
400     | Malformed_request req ->
401         respond_error
402           ~code:400
403           ~body:(
404             "request 1st line format should be: '<method> <url> <version>'" ^
405             "<br />\nwhile received request 1st line was:<br />\n" ^ req)
406           outchan
407     | Unsupported_method meth ->
408         respond_error
409           ~code:501
410           ~body:("Method '" ^ meth ^ "' isn't supported (yet)")
411           outchan
412     | Malformed_request_URI uri ->
413         respond_error ~code:400 ~body:("Malformed URL: '" ^ uri ^ "'") outchan
414     | Unsupported_HTTP_version version ->
415         respond_error
416           ~code:505
417           ~body:("HTTP version '" ^ version ^ "' isn't supported (yet)")
418           outchan
419     | Malformed_query query ->
420         respond_error
421           ~code:400 ~body:("Malformed query string '" ^ query ^ "'") outchan
422     | Malformed_query_binding (binding, query) ->
423         respond_error
424           ~code:400
425           ~body:(
426             sprintf "Malformed query element '%s' in query '%s'" binding query)
427           outchan
428   in
429   Unix.establish_server daemon_callback sockaddr
430
431 let start'
432   ?(addr = default_addr) ?(port = default_port)
433   ?(timeout = Some default_timeout)
434   (callback: (Types.request -> out_channel -> unit))
435   =
436   let wrapper path params outchan =
437     let req = new Request.request ~path ~params in
438     callback req outchan
439   in
440   start ~addr ~port ~timeout wrapper
441
442 module Trivial =
443   struct
444     let callback path _ outchan =
445       if not (Pcre.pmatch ~rex:(Pcre.regexp "^/") path) then
446         respond_error ~code:400 outchan
447       else
448         respond_file ~fname:(Misc.strip_heading_slash path) outchan
449     let start ?(addr = default_addr) ?(port = default_port) () =
450       start ~addr ~port callback
451   end
452