]> matita.cs.unibo.it Git - helm.git/blob - helm/DEVEL/ocaml-http/http_daemon.ml
changed interface of send_file function to enforce static type checking
[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 default_addr = "0.0.0.0"
30 let default_port = 80
31 let default_timeout = 300
32 let default_mode = `Fork
33
34   (** send raw data on outchan, flushing it afterwards *)
35 let send_raw ~data outchan =
36   output_string outchan data;
37   flush outchan
38
39 let send_CRLF = send_raw ~data:crlf
40
41 let send_header ~header ~value =
42   Http_parser_sanity.heal_header (header, value);
43   send_raw ~data:(header ^ ": " ^ value ^ crlf)
44
45 let send_headers ~headers outchan =
46   List.iter (fun (header, value) -> send_header ~header ~value outchan) headers
47
48   (** internal: parse a code argument from a function which have two optional
49   arguments "code" and "status" *)
50 let get_code_argument func_name =
51   fun ~code ~status ->
52     (match code, status with
53     | Some c, None -> c
54     | None, Some s -> code_of_status s
55     | Some _, Some _ -> (* TODO use some static type checking *)
56         failwith (func_name ^ " you must give 'code' or 'status', not both")
57     | None, None -> (* TODO use some static type checking *)
58         failwith (func_name ^ " you must give 'code' or 'status', not none"))
59
60   (** internal: low level for send_status_line *)
61 let send_status_line' ~version ~code =
62   let status_line =
63     String.concat
64       " "
65       [ string_of_version version;
66       string_of_int code;
67       Http_misc.reason_phrase_of_code code ]
68   in
69   send_raw ~data:(status_line ^ crlf)
70
71 let send_status_line ?(version = http_version) ?code ?status outchan =
72   send_status_line'
73     ~version
74     ~code:(get_code_argument "Daemon.send_status_line" ~code ~status)
75     outchan
76
77   (* FIXME duplication of code between this and response#addBasicHeaders *)
78 let send_basic_headers ?(version = http_version) ?code ?status outchan =
79   send_status_line'
80     ~version ~code:(get_code_argument "Daemon.send_basic_headers" ~code ~status)
81     outchan;
82   send_headers
83     ~headers:["Date", Http_misc.date_822 (); "Server", server_string]
84     outchan
85
86   (** internal: given a status code and an additional body return a string
87   representing an HTML document that explains the meaning of given status code.
88   Additional data can be added to the body via 'body' argument *)
89 let foo_body code body =
90   let reason_phrase = Http_misc.reason_phrase_of_code code in
91   sprintf
92 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
93 <HTML><HEAD>
94 <TITLE>%d %s</TITLE>
95 </HEAD><BODY>
96 <H1>%d - %s</H1>%s
97 </BODY></HTML>"
98     code reason_phrase code reason_phrase body
99
100   (** internal: send a fooish body explaining in HTML form the 'reason phrase'
101   of an HTTP response; body, if given, will be appended to the body *)
102 let send_foo_body code body = send_raw ~data:(foo_body code body)
103
104 let respond
105   (* Warning: keep default values in sync with Http_response.response class *)
106   ?(body = "") ?(headers = [])
107   ?(version = http_version) ?(code = 200) ?status outchan
108   =
109   let code =
110     match status with
111     | None -> code
112     | Some s -> code_of_status s
113   in
114   send_basic_headers ~version ~code outchan;
115   send_headers ~headers outchan;
116   send_header "Content-Length" (string_of_int (String.length body)) outchan;
117   send_CRLF outchan;
118   send_raw ~data:body outchan
119
120   (** internal: low level for respond_redirect, respond_error, ...
121   This function send a status line corresponding to a given code, some basic
122   headers, the additional headers (if given) and an HTML page containing the
123   reason phrase; if body is given it will be included in the body of the HTML
124   page *)
125 let send_empty_response
126   func_name ?(is_valid_status = fun _ -> true) ?(headers = []) ~body () =
127     fun ?(version = http_version) ?code ?status outchan ->
128       let code = get_code_argument func_name ~code ~status in
129       if not (is_valid_status code) then
130         failwith
131           (sprintf "'%d' isn't a valid status code for %s" code func_name)
132       else begin  (* status code suitable for answering *)
133         let headers =
134           [
135             "Connection", "close";
136             "Content-Type", "text/html; charset=iso-8859-1"
137           ] @ headers
138         in
139         let body = (foo_body code body) ^ body in
140         respond ~version ~code ~headers ~body outchan
141 (*
142         (* OLD VERSION, now use 'respond' function *)
143         send_basic_headers ~version ~code outchan;
144         send_header ~header:"Connection" ~value:"close" outchan;
145         send_header
146           ~header:"Content-Type"
147           ~value:"text/html; charset=iso-8859-1"
148           outchan;
149         send_headers ~headers outchan;
150         send_CRLF outchan;
151         send_foo_body ~code ~body outchan
152 *)
153       end
154
155 let respond_redirect
156   ~location ?(body = "") ?(version = http_version) ?(code = 301) ?status outchan
157   =
158   let code = 
159     match status with
160     | None -> code
161     | Some (s: Http_types.redirection_status) -> code_of_status s
162   in
163   send_empty_response
164     "Daemon.respond_redirect" ~is_valid_status:is_redirection
165     ~headers:["Location", location] ~body ()
166     ~version ~code outchan
167
168 let respond_error
169   ?(body = "") ?(version = http_version) ?(code = 400) ?status outchan =
170     let code =
171       match status with
172       | None -> code
173       | Some s -> code_of_status s
174     in
175     send_empty_response
176       "Daemon.respond_error" ~is_valid_status:is_error ~body ()
177       ~version ~code outchan
178
179 let respond_not_found ~url ?(version = http_version) outchan =
180   send_empty_response
181     "Daemon.respond_not_found" ~body:"" () ~version ~code:404 outchan
182
183 let respond_forbidden ~url ?(version = http_version) outchan =
184   send_empty_response
185     "Daemon.respond_permission_denied" ~body:"" () ~version ~code:403 outchan
186
187 (* let send_file ?name ?file outchan = *)
188 let send_file ~src outchan =
189   let buflen = 1024 in
190   let buf = String.make buflen ' ' in
191 (*
192   let (file, cleanup) =
193     (match (name, file) with
194     | Some n, None -> (* if we open the file, we close it before returning *)
195         let f = open_in n in
196         f, (fun () -> close_in f)
197     | None, Some f -> (f, (fun () -> ()))
198     | _ ->  (* TODO use some static type checking *)
199         failwith "Daemon.send_file: either name or file must be given")
200   in
201 *)
202   let (file, cleanup) =
203     match src with
204     | FileSrc fname -> (* if we open the file, we close it before returning *)
205         let f = open_in fname in
206         f, (fun () -> close_in f)
207     | InChanSrc inchan -> inchan, ignore
208   in
209   try
210     while true do
211       let bytes = input file buf 0 buflen in
212       if bytes = 0 then
213         raise End_of_file
214       else
215         output outchan buf 0 bytes
216     done;
217     assert false
218   with End_of_file ->
219     begin
220       flush outchan;
221       cleanup ()
222     end
223
224   (* TODO interface is too ugly to advertise this function in .mli *)
225   (** create a minimal HTML directory listing of a given directory and send it
226   over an out_channel, directory is passed as a dir_handle; name is the
227   directory name, used for pretty printing purposes; path is the opened dir
228   path, used to test its contents with stat *)
229 let send_dir_listing ~dir ~name ~path outchan =
230   fprintf outchan "<html>\n<head><title>%s</title></head>\n<body>\n" name;
231   let (dirs, files) =
232     List.partition (fun e -> Http_misc.is_directory (path ^ e)) (Http_misc.ls dir)
233   in
234   List.iter
235     (fun d -> fprintf outchan "<a href=\"%s/\">%s/</a><br />\n" d d)
236     (List.sort compare dirs);
237   List.iter
238     (fun f -> fprintf outchan "<a href=\"%s\">%s</a><br />\n" f f)
239     (List.sort compare files);
240   fprintf outchan "</body>\n</html>";
241   flush outchan
242
243 let respond_file ~fname ?(version = http_version) outchan =
244   (** ASSUMPTION: 'fname' doesn't begin with a "/"; it's relative to the current
245   document root (usually the daemon's cwd) *)
246   let droot = Sys.getcwd () in  (* document root *)
247   let path = droot ^ "/" ^ fname in (* full path to the desired file *)
248   if not (Sys.file_exists path) then (* file not found *)
249     respond_not_found ~url:fname outchan
250   else begin
251     try
252       if Http_misc.is_directory path then begin (* file found, is a dir *)
253         let dir = Unix.opendir path in
254         send_basic_headers ~version ~code:200 outchan;
255         send_header "Content-Type" "text/html" outchan;
256         send_CRLF outchan;
257         send_dir_listing ~dir ~name:fname ~path outchan;
258         Unix.closedir dir
259       end else begin  (* file found, is something else *)
260         let file = open_in fname in
261         send_basic_headers ~version ~code:200 outchan;
262         send_header
263           ~header:"Content-Length"
264           ~value:(string_of_int (Http_misc.filesize fname))
265           outchan;
266         send_CRLF outchan;
267         send_file ~src:(InChanSrc file) outchan;
268         close_in file
269       end
270     with
271     | Unix.Unix_error (Unix.EACCES, s, _) when (s = fname) ->
272         respond_forbidden ~url:fname ~version outchan
273     | Sys_error s when
274         (Pcre.pmatch ~rex:(Pcre.regexp (fname ^ ": Permission denied")) s) ->
275           respond_forbidden ~url:fname ~version outchan
276   end
277
278 let respond_with (res: Http_types.response) outchan =
279   res#serialize outchan;
280   flush outchan
281
282   (** internal: this exception is raised after a malformed request has been read
283   by a serving process to signal main server (or itself if mode = `Single) to
284   skip to next request *)
285 exception Again;;
286
287 let pp_parse_exc e =
288   sprintf "HTTP request parse error: %s" (Printexc.to_string e)
289
290   (* given a Http_parser.parse_request like function, wrap it in a function that
291   do the same and additionally catch parsing exception sending HTTP error
292   messages back to client as needed. Returned function raises Again when it
293   encounter a parse error (name 'Again' is intended for future versions that
294   will support http keep alive signaling that a new request has to be parsed
295   from client) *)
296 let rec wrap_parse_request_w_safety parse_function inchan outchan =
297 (*   try *)
298   (try
299     parse_function inchan
300   with
301   | (End_of_file) as e ->
302       debug_print (pp_parse_exc e);
303       respond_error ~code:400 ~body:"Unexpected End Of File" outchan;
304       raise Again
305   | (Malformed_request req) as e ->
306       debug_print (pp_parse_exc e);
307       respond_error
308         ~code:400
309         ~body:(
310           "request 1st line format should be: '<method> <url> <version>'" ^
311           "<br />\nwhile received request 1st line was:<br />\n" ^ req)
312         outchan;
313       raise Again
314   | (Invalid_HTTP_method meth) as e ->
315       debug_print (pp_parse_exc e);
316       respond_error
317         ~code:501
318         ~body:("Method '" ^ meth ^ "' isn't supported (yet)")
319         outchan;
320       raise Again
321   | (Malformed_request_URI uri) as e ->
322       debug_print (pp_parse_exc e);
323       respond_error ~code:400 ~body:("Malformed URL: '" ^ uri ^ "'") outchan;
324       raise Again
325   | (Invalid_HTTP_version version) as e ->
326       debug_print (pp_parse_exc e);
327       respond_error
328         ~code:505
329         ~body:("HTTP version '" ^ version ^ "' isn't supported (yet)")
330         outchan;
331       raise Again
332   | (Malformed_query query) as e ->
333       debug_print (pp_parse_exc e);
334       respond_error
335         ~code:400 ~body:(sprintf "Malformed query string '%s'" query) outchan;
336       raise Again
337   | (Malformed_query_part (binding, query)) as e ->
338       debug_print (pp_parse_exc e);
339       respond_error
340         ~code:400
341         ~body:(
342           sprintf "Malformed query part '%s' in query '%s'" binding query)
343         outchan;
344       raise Again)
345 (*  (* preliminary support for HTTP keep alive connections ... *)
346   with Again ->
347     wrap_parse_request_w_safety parse_function inchan outchan
348 *)
349
350   (* wrapper around Http_parser.parse_request which catch parsing exceptions and
351   return error messages to client as needed
352   @param inchan in_channel from which read incoming requests
353   @param outchan out_channl on which respond with error messages if needed
354   *)
355 let safe_parse_request = wrap_parse_request_w_safety parse_request
356
357   (* as above but for OO version (Http_parser.parse_request') *)
358 let safe_parse_request' = wrap_parse_request_w_safety (new Http_request.request)
359
360 let chdir_to_document_root = function (* chdir to document root *)
361   | Some dir -> Sys.chdir dir
362   | None -> ()
363
364 let server_of_mode = function
365   | `Single -> Http_tcp_server.simple
366   | `Fork   -> Http_tcp_server.fork
367   | `Thread -> Http_tcp_server.thread
368
369   (* TODO what happens when a Quit exception is raised by a callback? Do other
370   callbacks keep on living until the end or are them all killed immediatly?
371   The right semantics should obviously be the first one *)
372
373   (* TODO support also chroot to 'root', not only chdir *)
374   (* curried request *)
375 let start
376   ?(addr = default_addr) ?(port = default_port)
377   ?(timeout = Some default_timeout) ?(mode = default_mode) ?root callback
378   =
379   chdir_to_document_root root;
380   let sockaddr = Http_misc.build_sockaddr (addr, port) in
381   let daemon_callback inchan outchan =
382     try
383       let (path, parameters) = safe_parse_request inchan outchan in
384       callback path parameters outchan;
385       flush outchan
386     with Again -> ()
387   in
388   try
389     (server_of_mode mode) ~sockaddr ~timeout daemon_callback 
390   with Quit -> ()
391
392   (* OO request *)
393 let start'
394   ?(addr = default_addr) ?(port = default_port)
395   ?(timeout = Some default_timeout) ?(mode = default_mode) ?root callback
396   =
397   chdir_to_document_root root;
398   let sockaddr = Http_misc.build_sockaddr (addr, port) in
399   let daemon_callback inchan outchan =
400     try
401       let req = safe_parse_request' inchan outchan in
402       callback req outchan;
403       flush outchan
404     with Again -> ()
405   in
406   try
407     (server_of_mode mode) ~sockaddr ~timeout daemon_callback 
408   with Quit -> ()
409
410 module Trivial =
411   struct
412     let callback path _ outchan =
413       if not (Pcre.pmatch ~rex:(Pcre.regexp "^/") path) then
414         respond_error ~code:400 outchan
415       else
416         respond_file ~fname:(Http_misc.strip_heading_slash path) outchan
417     let start ?(addr = default_addr) ?(port = default_port) () =
418       start ~addr ~port callback
419   end
420
421   (* @param inchan input channel connected to client
422      @param outchan output channel connected to client
423      @param sockaddr client socket address *)
424 class connection inchan outchan sockaddr =
425   (* ASSUMPTION: inchan and outchan are channels built on top of the same
426   Unix.file_descr thus closing one of them will close also the other *)
427   let close' o = o#close in
428   object (self)
429
430     initializer Gc.finalise close' self
431
432     val mutable closed = false
433
434     method private assertNotClosed =
435       if closed then
436         failwith "Http_daemon.connection: connection is closed"
437
438     method getRequest =
439       self#assertNotClosed;
440       try
441         Some (safe_parse_request' inchan outchan)
442       with Again -> None
443
444     method respond_with res =
445       self#assertNotClosed;
446       respond_with res outchan
447
448     method close =
449       self#assertNotClosed;
450       close_in inchan;  (* this close also outchan *)
451       closed <- true
452
453   end
454
455 class daemon ?(addr = "0.0.0.0") ?(port = 80) () =
456   object (self)
457
458     val suck =
459       Http_tcp_server.init_socket (Http_misc.build_sockaddr (addr, port))
460
461     method accept =
462       let (cli_suck, cli_sockaddr) = Unix.accept suck in  (* may block *)
463       let (inchan, outchan) =
464         (Unix.in_channel_of_descr cli_suck, Unix.out_channel_of_descr cli_suck)
465       in
466       new connection inchan outchan cli_sockaddr
467
468     method getRequest =
469       let conn = self#accept in
470       match conn#getRequest with
471       | None ->
472           conn#close;
473           self#getRequest
474       | Some req -> (req, conn)
475
476   end
477