]> matita.cs.unibo.it Git - helm.git/blob - helm/DEVEL/ocaml-http/http_daemon.ml
renamed tcp_server module in http_tcp_server to avoid future
[helm.git] / helm / DEVEL / ocaml-http / 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 Printf;;
23
24 open Http_parser;;
25
26 let debug = true
27 let debug_print str =
28   if debug then begin
29     prerr_endline ("DEBUG: " ^ str);
30     flush stderr
31   end
32
33 let default_addr = "0.0.0.0"
34 let default_port = 80
35 let default_timeout = 300
36 let default_fork = true
37
38   (** send raw data on outchan, flushing it afterwards *)
39 let send_raw ~data outchan =
40   output_string outchan data;
41   flush outchan
42
43 let send_CRLF = send_raw ~data:Http_common.crlf
44
45   (** TODO perform some sanity test on header and value *)
46 let send_header ~header ~value =
47   send_raw ~data:(header ^ ": " ^ value ^ Http_common.crlf)
48
49 let send_headers ~headers outchan =
50   List.iter (fun (header, value) -> send_header ~header ~value outchan) headers
51
52   (** internal: parse a code argument from a function which have two optional
53   arguments "code" and "status" *)
54 let get_code_argument func_name =
55   fun ~code ~status ->
56     (match code, status with
57     | Some c, None -> c
58     | None, Some s -> Http_common.code_of_status s
59     | Some _, Some _ ->
60         failwith (func_name ^ " you must give 'code' or 'status', not both")
61     | None, None ->
62         failwith (func_name ^ " you must give 'code' or 'status', not none"))
63
64   (** internal: low level for send_status_line *)
65 let send_status_line' ~version ~code =
66   let status_line =
67     String.concat
68       " "
69       [ Http_common.string_of_version version;
70       string_of_int code;
71       Http_common.reason_phrase_of_code code ]
72   in
73   send_raw ~data:(status_line ^ Http_common.crlf)
74
75 let send_status_line
76   ?(version = Http_common.http_version) ?code ?status outchan
77   =
78   send_status_line'
79     ~version
80     ~code:(get_code_argument "Daemon.send_status_line" ~code ~status)
81     outchan
82
83   (* FIXME duplication of code between this and response#addBasicHeaders *)
84 let send_basic_headers
85   ?(version = Http_common.http_version) ?code ?status outchan
86   =
87   send_status_line'
88     ~version ~code:(get_code_argument "Daemon.send_basic_headers" ~code ~status)
89     outchan;
90   send_headers
91     ~headers:["Date", Http_misc.date_822 (); "Server", Http_common.server_string]
92     outchan
93
94   (** internal: send a fooish body explaining in HTML form the 'reason phrase'
95   of an HTTP response; body, if given, will be appended to the body *)
96 let send_foo_body ~code ~body =
97   let reason_phrase = Http_common.reason_phrase_of_code code in
98   let body =
99     sprintf
100 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
101 <HTML><HEAD>
102 <TITLE>%d %s</TITLE>
103 </HEAD><BODY>
104 <H1>%d - %s</H1>%s
105 </BODY></HTML>"
106       code reason_phrase code reason_phrase
107       (match body with None -> "" | Some text -> "\n" ^ text)
108   in
109   send_raw ~data:body
110
111   (** internal: low level for respond_redirect, respond_error, ...
112   This function send a status line corresponding to a given code, some basic
113   headers, the additional headers (if given) and an HTML page containing the
114   reason phrase; if body is given it will be included in the body of the HTML
115   page *)
116 let send_empty_response
117   f_name ?(is_valid_status = fun _ -> true) ?(headers = []) ~body () =
118     fun ?(version = Http_common.http_version) ?code ?status outchan ->
119       let code = get_code_argument f_name ~code ~status in
120       if not (is_valid_status code) then
121         failwith (sprintf "'%d' isn't a valid status code for %s" code f_name)
122       else begin  (* status code suitable for answering *)
123         send_basic_headers ~version ~code outchan;
124         send_header ~header:"Connection" ~value:"close" outchan;
125         send_header
126           ~header:"Content-Type"
127           ~value:"text/html; charset=iso-8859-1"
128           outchan;
129         send_headers ~headers outchan;
130         send_CRLF outchan;
131         send_foo_body ~code ~body outchan
132       end
133
134   (* TODO sanity tests on location *)
135 let respond_redirect
136   ~location ?body
137   ?(version = Http_common.http_version) ?(code = 301) ?status outchan =
138     let code = 
139       match status with
140       | None -> code
141       | Some (s: Http_types.redirection_status) -> Http_common.code_of_status s
142     in
143     send_empty_response
144       "Daemon.respond_redirect" ~is_valid_status:Http_common.is_redirection
145       ~headers:["Location", location] ~body ()
146       ~version ~code outchan
147
148 let respond_error
149   ?body
150   ?(version = Http_common.http_version) ?(code = 400) ?status outchan =
151     let code =
152       match status with
153       | None -> code
154       | Some s -> Http_common.code_of_status s
155     in
156     send_empty_response
157       "Daemon.respond_error" ~is_valid_status:Http_common.is_error ~body ()
158       ~version ~code outchan
159
160 let respond_not_found ~url ?(version = Http_common.http_version) outchan =
161   send_empty_response
162     "Daemon.respond_not_found" ~body:None ()
163     ~version ~code:404 outchan
164
165 let respond_forbidden ~url ?(version = Http_common.http_version) outchan =
166   send_empty_response
167     "Daemon.respond_permission_denied" ~body:None ()
168     ~version ~code:403 outchan
169
170 let send_file ?name ?file outchan =
171   let buflen = 1024 in
172   let buf = String.make buflen ' ' in
173   let (file, cleanup) =
174     (match (name, file) with
175     | Some n, None -> (* if we open the file, we close it before returning *)
176         let f = open_in n in
177         f, (fun () -> close_in f)
178     | None, Some f -> (f, (fun () -> ()))
179     | _ -> failwith "Daemon.send_file: either name or file must be given")
180   in
181   try
182     while true do
183       let bytes = input file buf 0 buflen in
184       if bytes = 0 then
185         raise End_of_file
186       else
187         output outchan buf 0 bytes
188     done;
189     assert false
190   with End_of_file ->
191     begin
192       flush outchan;
193       cleanup ()
194     end
195
196   (* TODO interface is too ugly to advertise this function in .mli *)
197   (** create a minimal HTML directory listing of a given directory and send it
198   over an out_channel, directory is passed as a dir_handle; name is the
199   directory name, used for pretty printing purposes; path is the opened dir
200   path, used to test its contents with stat *)
201 let send_dir_listing ~dir ~name ~path outchan =
202   fprintf outchan "<html>\n<head><title>%s</title></head>\n<body>\n" name;
203   let (dirs, files) =
204     List.partition (fun e -> Http_misc.is_directory (path ^ e)) (Http_misc.ls dir)
205   in
206   List.iter
207     (fun d -> fprintf outchan "<a href=\"%s/\">%s/</a><br />\n" d d)
208     (List.sort compare dirs);
209   List.iter
210     (fun f -> fprintf outchan "<a href=\"%s\">%s</a><br />\n" f f)
211     (List.sort compare files);
212   fprintf outchan "</body>\n</html>";
213   flush outchan
214
215 let respond_file ~fname ?(version = Http_common.http_version) outchan =
216   (** ASSUMPTION: 'fname' doesn't begin with a "/"; it's relative to the current
217   document root (usually the daemon's cwd) *)
218   let droot = Sys.getcwd () in  (* document root *)
219   let path = droot ^ "/" ^ fname in (* full path to the desired file *)
220   if not (Sys.file_exists path) then (* file not found *)
221     respond_not_found ~url:fname outchan
222   else begin
223     try
224       if Http_misc.is_directory path then begin (* file found, is a dir *)
225         let dir = Unix.opendir path in
226         send_basic_headers ~version ~code:200 outchan;
227         send_header "Content-Type" "text/html" outchan;
228         send_CRLF outchan;
229         send_dir_listing ~dir ~name:fname ~path outchan;
230         Unix.closedir dir
231       end else begin  (* file found, is something else *)
232         let file = open_in fname in
233         send_basic_headers ~version ~code:200 outchan;
234         send_header
235           ~header:"Content-Length"
236           ~value:(string_of_int (Http_misc.filesize fname))
237           outchan;
238         send_CRLF outchan;
239         send_file ~file outchan;
240         close_in file
241       end
242     with
243     | Unix.Unix_error (Unix.EACCES, s, _) when (s = fname) ->
244         respond_forbidden ~url:fname ~version outchan
245     | Sys_error s when
246         (Pcre.pmatch ~rex:(Pcre.regexp (fname ^ ": Permission denied")) s) ->
247           respond_forbidden ~url:fname ~version outchan
248   end
249
250 let respond_with (res: Http_types.response) outchan =
251   res#serialize outchan;
252   flush outchan
253
254   (* curried request *)
255 let start
256   ?(addr = default_addr) ?(port = default_port)
257   ?(timeout = Some default_timeout) ?(fork = default_fork)
258   callback
259   =
260   let sockaddr = Unix.ADDR_INET (Unix.inet_addr_of_string addr, port) in
261   let daemon_callback inchan outchan =
262     try
263       let (path, parameters) = Http_parser.parse_request inchan in
264       callback path parameters outchan;
265       flush outchan
266     with
267     | End_of_file ->
268         respond_error ~code:400 ~body:"Unexpected End Of File" outchan
269     | Malformed_request req ->
270         respond_error
271           ~code:400
272           ~body:(
273             "request 1st line format should be: '<method> <url> <version>'" ^
274             "<br />\nwhile received request 1st line was:<br />\n" ^ req)
275           outchan
276     | Unsupported_method meth ->
277         respond_error
278           ~code:501
279           ~body:("Method '" ^ meth ^ "' isn't supported (yet)")
280           outchan
281     | Malformed_request_URI uri ->
282         respond_error ~code:400 ~body:("Malformed URL: '" ^ uri ^ "'") outchan
283     | Unsupported_HTTP_version version ->
284         respond_error
285           ~code:505
286           ~body:("HTTP version '" ^ version ^ "' isn't supported (yet)")
287           outchan
288     | Malformed_query query ->
289         respond_error
290           ~code:400 ~body:("Malformed query string '" ^ query ^ "'") outchan
291     | Malformed_query_binding (binding, query) ->
292         respond_error
293           ~code:400
294           ~body:(
295             sprintf "Malformed query element '%s' in query '%s'" binding query)
296           outchan
297   in
298   match fork with
299   | true -> Http_tcp_server.ocaml_builtin ~sockaddr ~timeout daemon_callback 
300   | false -> Http_tcp_server.simple ~sockaddr ~timeout daemon_callback
301
302   (* OO request *)
303 let start'
304   ?(addr = default_addr) ?(port = default_port)
305   ?(timeout = Some default_timeout) ?(fork = default_fork)
306   (callback: (Http_types.request -> out_channel -> unit))
307   =
308   let wrapper path params outchan =
309     let req = new Http_request.request ~path ~params in
310     callback req outchan
311   in
312   start ~addr ~port ~timeout ~fork wrapper
313
314 module Trivial =
315   struct
316     let callback path _ outchan =
317       if not (Pcre.pmatch ~rex:(Pcre.regexp "^/") path) then
318         respond_error ~code:400 outchan
319       else
320         respond_file ~fname:(Http_misc.strip_heading_slash path) outchan
321     let start ?(addr = default_addr) ?(port = default_port) () =
322       start ~addr ~port callback
323   end
324