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