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