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