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