]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/main.ml
use latest Http_getter module API
[helm.git] / helm / http_getter / main.ml
1 (*
2  * Copyright (C) 2003-2004:
3  *    Stefano Zacchiroli <zack@cs.unibo.it>
4  *    for the HELM Team http://helm.cs.unibo.it/
5  *
6  *  This file is part of HELM, an Hypertextual, Electronic
7  *  Library of Mathematics, developed at the Computer Science
8  *  Department, University of Bologna, Italy.
9  *
10  *  HELM is free software; you can redistribute it and/or
11  *  modify it under the terms of the GNU General Public License
12  *  as published by the Free Software Foundation; either version 2
13  *  of the License, or (at your option) any later version.
14  *
15  *  HELM is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with HELM; if not, write to the Free Software
22  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23  *  MA  02111-1307, USA.
24  *
25  *  For details, see the HELM World-Wide-Web page,
26  *  http://helm.cs.unibo.it/
27  *)
28
29 open Printf
30
31 open Http_getter_common
32 open Http_getter_misc
33 open Http_getter_types
34
35   (* constants *)
36
37 let configuration_file = BuildTimeOpts.conffile
38
39 let common_headers = [
40   "Cache-Control", "no-cache";
41   "Pragma", "no-cache";
42   "Expires", "0"
43 ]
44
45   (* HTTP queries argument parsing *)
46
47   (* parse encoding ("format" parameter), default is `Normal *)
48 let parse_enc (req: Http_types.request) =
49   try
50     (match req#param "format" with
51     | "normal" -> `Normal
52     | "gz" -> `Gzipped
53     | s -> raise (Bad_request ("Invalid format: " ^ s)))
54   with Http_types.Param_not_found _ -> `Normal
55
56   (* parse "patch_dtd" parameter, default is true *)
57 let parse_patch (req: Http_types.request) =
58   try
59     (match req#param "patch_dtd" with
60     | s when String.lowercase s = "yes" -> true
61     | s when String.lowercase s = "no" -> false
62     | s -> raise (Bad_request ("Invalid patch_dtd value: " ^ s)))
63   with Http_types.Param_not_found _ -> true
64
65   (* parse output format ("format" parameter), no default value *)
66 let parse_output_format meth (req: Http_types.request) =
67   match req#param "format" with
68   | s when String.lowercase s = "txt" -> `Text
69   | s when String.lowercase s = "xml" -> `Xml
70   | s -> raise (Bad_request ("Invalid /" ^ meth ^ " format: " ^ s))
71
72   (* parse "position" argument, default is 0 *)
73 let parse_position (req: Http_types.request) =
74   try
75     let res = int_of_string (req#param "position") in
76     if res < 0 then
77       raise (Failure "int_of_string");
78     res
79   with
80   | Http_types.Param_not_found _ -> 0
81   | Failure "int_of_string" ->
82     raise (Bad_request
83       (sprintf "position must be a non negative integer (%s given)"
84         (req#param "position")))
85
86 let parse_rdf_class (req: Http_types.request) =
87   match req#param "class" with
88   | "forward" -> `Forward
89   | "backward" -> `Backward
90   | c -> raise (Bad_request ("Invalid RDF class: " ^ c))
91
92 let mk_return_fun pp_fun contype msg outchan =
93   Http_daemon.respond
94     ~body:(pp_fun msg) ~headers:["Content-Type", contype] outchan
95 let pp_error s =
96   sprintf "<html><body>Http Getter error: <span style=\"color:red\">%s</span></body></html>" s
97 let pp_internal_error s =
98   sprintf "<html><body>Http Getter Internal error: <span style=\"color:red\">%s</span></body></html>" s
99 let pp_msg s = sprintf "<html><body>%s</body></html>" s
100 let null_pp s = s
101 let return_html_error = mk_return_fun pp_error "text/html"
102 let return_html_internal_error = mk_return_fun pp_internal_error "text/html"
103 let return_html_msg = mk_return_fun pp_msg "text/html"
104 let return_html_raw = mk_return_fun null_pp "text/html"
105 let return_xml_raw = mk_return_fun null_pp "text/xml"
106 let return_400 body outchan =
107   Http_daemon.respond_error ~code:(`Code 400) ~body outchan
108
109 let return_all_foo_uris doctype uris outchan =
110   Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
111   Http_daemon.send_header "Content-Type" "text/xml" outchan;
112   Http_daemon.send_headers common_headers outchan;
113   Http_daemon.send_CRLF outchan;
114   output_string
115     outchan
116     (sprintf
117 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
118 <!DOCTYPE %s SYSTEM \"%s/getdtd?uri=%s.dtd\">
119
120 <%s>
121 "
122       doctype
123       (Lazy.force Http_getter_env.my_own_url)
124       doctype
125       doctype);
126   List.iter
127     (fun uri -> output_string outchan (sprintf "\t<uri value=\"%s\" />\n" uri))
128     uris;
129   output_string outchan (sprintf "</%s>\n" doctype)
130
131 let return_all_xml_uris fmt outchan =
132  let uris = Http_getter.getalluris () in
133   match fmt with
134    | `Text ->
135       let buf = Buffer.create 10240 in
136        List.iter (bprintf buf "%s\n") uris ;
137        let body = Buffer.contents buf in
138        Http_daemon.respond
139          ~headers:(("Content-Type", "text/plain") :: common_headers)
140          ~body outchan
141    | `Xml ->
142       return_all_foo_uris "alluris" uris outchan
143   
144 let return_all_rdf_uris classs outchan =
145   return_all_foo_uris "allrdfuris" (Http_getter.getallrdfuris classs) outchan
146
147 let return_ls regexp fmt outchan =
148   let ls_items = Http_getter.ls regexp in
149   let buf = Buffer.create 10240 in
150   (match fmt with
151   | `Text ->
152       List.iter
153         (function
154           | Ls_section dir -> bprintf buf "dir, %s\n" dir
155           | Ls_object obj ->
156               bprintf buf "object, %s, <%s,%s,%s,%s>\n"
157               obj.uri (if obj.ann then "YES" else "NO")
158               (string_of_ls_flag obj.types)
159               (string_of_ls_flag obj.body)
160               (string_of_ls_flag obj.proof_tree))
161         ls_items
162   | `Xml ->
163       Buffer.add_string buf "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
164       bprintf buf "<!DOCTYPE ls SYSTEM \"%s/getdtd?uri=ls.dtd\">\n"
165         (Lazy.force Http_getter_env.my_own_url);
166       Buffer.add_string buf "<ls>\n";
167       List.iter
168         (function
169           | Ls_section dir -> bprintf buf "<section>%s</section>\n" dir
170           | Ls_object obj ->
171               bprintf buf
172 "<object name=\"%s\">
173 \t<ann value=\"%s\" />
174 \t<types value=\"%s\" />
175 \t<body value=\"%s\" />
176 \t<proof_tree value=\"%s\" />
177 </object>
178 "
179               obj.uri (if obj.ann then "YES" else "NO")
180               (string_of_ls_flag obj.types)
181               (string_of_ls_flag obj.body)
182               (string_of_ls_flag obj.proof_tree))
183         ls_items;
184       Buffer.add_string buf "</ls>\n");
185   let body = Buffer.contents buf in
186   Http_daemon.respond
187     ~headers:(("Content-Type", "text/plain") :: common_headers)
188     ~body outchan
189
190 let return_help outchan = return_html_raw (Http_getter.help ()) outchan
191
192 let return_resolve uri outchan =
193   try
194     return_xml_raw
195       (sprintf "<url value=\"%s\" />\n" (Http_getter.resolve uri))
196       outchan
197   with
198   | Unresolvable_URI _ -> return_xml_raw "<unresolvable />\n" outchan
199   | Key_not_found _ -> return_xml_raw "<not_found />\n" outchan
200
201 let return_list_servers outchan =
202   return_html_raw
203     (sprintf "<html><body><table>\n%s\n</table></body></html>"
204       (String.concat "\n"
205         (List.map
206           (fun (pos, server) ->
207             sprintf "<tr><td>%d</td><td>%s</td></tr>" pos server)
208           (Http_getter.list_servers ()))))
209     outchan
210
211 let log_failure msg = Http_getter_logger.log ("Request not fulfilled: " ^ msg)
212
213   (** given an action (i.e. a function which expects a logger and do something
214    * using it as a logger), perform it sending its output incrementally to the
215    * given output channel. Response is sent embedded in an HTML document.
216    * Channel is closed afterwards. *)
217 let send_log_to ?prepend action outchan =
218   Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
219   Http_daemon.send_header "Content-Type" "text/html" outchan;
220   Http_daemon.send_CRLF outchan;
221   output_string outchan "<html><body>\n"; flush outchan;
222   (match prepend with
223   | None -> ()
224   | Some text -> output_string outchan text; flush outchan);
225   let logger tag =
226     output_string outchan (HelmLogger.html_of_html_tag tag);
227     flush outchan
228   in
229   action logger;
230   output_string outchan "\n</body></html>";
231   close_out outchan
232
233   (* thread action *)
234
235 let callback (req: Http_types.request) outchan =
236   try
237     Http_getter_logger.log ("Connection from " ^ req#clientAddr);
238     Http_getter_logger.log ("Received request: " ^ req#path);
239     (match req#path with
240     | "/help" -> return_help outchan
241     | "/getxml" ->
242         let uri = req#param "uri" in
243         Http_getter_cache.respond_xml ~url:(Http_getter.resolve uri) ~uri
244           ~enc:(parse_enc req) ~patch:(parse_patch req) outchan
245     | "/getxslt" ->
246         Http_getter_cache.respond_xsl
247           ~url:(Http_getter.resolve (req#param "uri"))
248           ~patch:(parse_patch req) outchan
249     | "/getdtd" ->
250         Http_getter_cache.respond_dtd ~patch:(parse_patch req)
251           ~url:(sprintf "%s/%s"
252             (Helm_registry.get "getter.dtd_dir") (req#param "uri"))
253           outchan
254     | "/resolve" -> return_resolve (req#param "uri") outchan
255     | "/register" ->
256         Http_getter.register ~uri:(req#param "uri") ~url:(req#param "url");
257         return_html_msg "Register done" outchan
258     | "/unregister" ->
259         Http_getter.unregister (req#param "uri");
260         return_html_msg "Unregister done" outchan
261     | "/clean_cache" ->
262         Http_getter.clean_cache ();
263         return_html_msg "Done." outchan
264     | "/update" ->
265         Http_getter_env.reload (); (* reload servers list from servers file *)
266         send_log_to (fun logger -> Http_getter.update ~logger ()) outchan
267     | "/list_servers" -> return_list_servers outchan
268     | "/add_server" ->
269         let name = req#param "url" in
270         let position = parse_position req in
271         let prepend =
272           sprintf "Added server %s in position %d)<br />\n" name position
273         in
274         send_log_to ~prepend
275           (fun logger -> Http_getter.add_server ~logger ~position name) outchan
276     | "/remove_server" ->
277         let position = parse_position req in
278         if not (Http_getter.has_server position) then
279           raise (Bad_request (sprintf "no server with position %d" position))
280         else
281           let prepend =
282             sprintf "Removed server at position %d<br />\n" position
283           in
284           send_log_to ~prepend
285             (fun logger -> Http_getter.remove_server ~logger position) outchan
286     | "/getalluris" ->
287        return_all_xml_uris (parse_output_format "getalluris" req) outchan
288     | "/getallrdfuris" -> return_all_rdf_uris (parse_rdf_class req) outchan
289     | "/ls" ->
290         return_ls (req#param "baseuri") (parse_output_format "ls" req) outchan
291     | "/getempty" ->
292         Http_daemon.respond ~body:Http_getter_const.empty_xml outchan
293     | invalid_request ->
294         Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request))
295           outchan);
296     Http_getter_logger.log "Done!\n"
297   with
298   | Http_types.Param_not_found attr_name ->
299       let msg = sprintf "Parameter '%s' is missing" attr_name in
300       log_failure msg;
301       return_400 msg outchan
302   | Bad_request msg ->
303       log_failure msg;
304       return_html_error msg outchan
305   | Internal_error msg ->
306       log_failure msg;
307       return_html_internal_error msg outchan
308   | Shell.Subprocess_error l ->
309       let msgs =
310         List.map
311           (fun (cmd, code) ->
312             sprintf "Command '%s' returned %s" cmd (string_of_proc_status code))
313           l
314       in
315       log_failure (String.concat ", " msgs);
316       return_html_internal_error (String.concat "<br />\n" msgs) outchan
317   | exc ->
318       let msg = "Uncaught exception: " ^ (Printexc.to_string exc) in
319       log_failure msg;
320       return_html_error msg outchan
321
322     (* Main *)
323
324 let main () =
325   Helm_registry.load_from configuration_file;
326   Http_getter_logger.set_log_level
327     (Helm_registry.get_opt_default Helm_registry.get_int 1 "getter.log_level");
328   Http_getter_logger.set_log_file
329     (Helm_registry.get_opt Helm_registry.get_string "getter.log_file");
330   Http_getter_env.reload ();
331   print_string (Http_getter_env.env_to_string ());
332   flush stdout;
333   let batch_update =
334     try Sys.argv.(1) = "-update" with Invalid_argument _ -> false
335   in
336   if batch_update then  (* batch mode: performs update and exit *)
337     Http_getter.update ~logger:Http_getter.stdout_logger ()
338   else begin            (* daemon mode: start http daemon *)
339     at_exit Http_getter.close_maps;
340     Sys.catch_break true;
341     try
342       Http_daemon.start' ~mode:`Thread
343         ~timeout:(Some 600) ~port:(Helm_registry.get_int "getter.port")
344         callback
345     with Sys.Break -> ()  (* 'close_maps' already registered with 'at_exit' *)
346   end
347
348 let _ = main ()
349