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