]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/main.ml
- use new logger interface
[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 = "/projects/helm/etc/http_getter.conf.xml" *)
38 let configuration_file = "http_getter.conf.xml"
39
40 let common_headers = [
41   "Cache-Control", "no-cache";
42   "Pragma", "no-cache";
43   "Expires", "0"
44 ]
45
46   (* HTTP queries argument parsing *)
47
48   (* parse encoding ("format" parameter), default is `Normal *)
49 let parse_enc (req: Http_types.request) =
50   try
51     (match req#param "format" with
52     | "normal" -> `Normal
53     | "gz" -> `Gzipped
54     | s -> raise (Bad_request ("Invalid format: " ^ s)))
55   with Http_types.Param_not_found _ -> `Normal
56
57   (* parse "patch_dtd" parameter, default is true *)
58 let parse_patch (req: Http_types.request) =
59   try
60     (match req#param "patch_dtd" with
61     | s when String.lowercase s = "yes" -> true
62     | s when String.lowercase s = "no" -> false
63     | s -> raise (Bad_request ("Invalid patch_dtd value: " ^ s)))
64   with Http_types.Param_not_found _ -> true
65
66   (* parse output format ("format" parameter), no default value *)
67 let parse_output_format meth (req: Http_types.request) =
68   match req#param "format" with
69   | s when String.lowercase s = "txt" -> `Text
70   | s when String.lowercase s = "xml" -> `Xml
71   | s -> raise (Bad_request ("Invalid /" ^ meth ^ " format: " ^ s))
72
73   (* parse "baseuri" format for /ls method, no default value *)
74 let parse_ls_uri =
75   let parse_ls_RE = Pcre.regexp "^(\\w+):(.*)$" in
76   let trailing_slash_RE = Pcre.regexp "/+$" in
77   let wrong_uri uri =
78     raise (Bad_request ("Invalid /ls baseuri: " ^ uri))
79   in
80   fun (req: Http_types.request) ->
81     let baseuri = req#param "baseuri" in
82     try
83       let subs =
84         Pcre.extract ~rex:parse_ls_RE
85           (Pcre.replace ~rex:trailing_slash_RE  baseuri)
86       in
87       (match (subs.(1), subs.(2)) with
88       | "cic", uri -> Cic uri
89       | "theory", uri -> Theory uri
90       | _ -> wrong_uri baseuri)
91     with Not_found -> wrong_uri baseuri
92
93   (* parse "position" argument, default is 0 *)
94 let parse_position (req: Http_types.request) =
95   try
96     let res = int_of_string (req#param "position") in
97     if res < 0 then
98       raise (Failure "int_of_string");
99     res
100   with
101   | Http_types.Param_not_found _ -> 0
102   | Failure "int_of_string" ->
103     raise (Bad_request
104       (sprintf "position must be a non negative integer (%s given)"
105         (req#param "position")))
106
107 let parse_rdf_class (req: Http_types.request) =
108   match req#param "class" with
109   | "forward" -> `Forward
110   | "backward" -> `Backward
111   | c -> raise (Bad_request ("Invalid RDF class: " ^ c))
112
113 let mk_return_fun pp_fun contype msg outchan =
114   Http_daemon.respond
115     ~body:(pp_fun msg) ~headers:["Content-Type", contype] outchan
116 let pp_error s =
117   sprintf "<html><body>Http Getter error: <span style=\"color:red\">%s</span></body></html>" s
118 let pp_internal_error s =
119   sprintf "<html><body>Http Getter Internal error: <span style=\"color:red\">%s</span></body></html>" s
120 let pp_msg s = sprintf "<html><body>%s</body></html>" s
121 let null_pp s = s
122 let return_html_error = mk_return_fun pp_error "text/html"
123 let return_html_internal_error = mk_return_fun pp_internal_error "text/html"
124 let return_html_msg = mk_return_fun pp_msg "text/html"
125 let return_html_raw = mk_return_fun null_pp "text/html"
126 let return_xml_raw = mk_return_fun null_pp "text/xml"
127 let return_400 body outchan = Http_daemon.respond_error ~code:400 ~body outchan
128
129 let return_all_foo_uris doctype uris outchan =
130   Http_daemon.send_basic_headers ~code:200 outchan;
131   Http_daemon.send_header "Content-Type" "text/xml" outchan;
132   Http_daemon.send_headers common_headers outchan;
133   Http_daemon.send_CRLF outchan;
134   output_string
135     outchan
136     (sprintf
137 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
138 <!DOCTYPE %s SYSTEM \"%s/getdtd?uri=%s.dtd\">
139
140 <%s>
141 "
142       doctype
143       (Lazy.force Http_getter_env.my_own_url)
144       doctype
145       doctype);
146   List.iter
147     (fun uri -> output_string outchan (sprintf "\t<uri value=\"%s\" />\n" uri))
148     uris;
149   output_string outchan (sprintf "</%s>\n" doctype)
150
151 let return_all_xml_uris fmt outchan =
152  let uris = Http_getter.getalluris () in
153   match fmt with
154    | `Text ->
155       let buf = Buffer.create 10240 in
156        List.iter (bprintf buf "%s\n") uris ;
157        let body = Buffer.contents buf in
158        Http_daemon.respond
159          ~headers:(("Content-Type", "text/plain") :: common_headers)
160          ~body outchan
161    | `Xml ->
162       return_all_foo_uris "alluris" uris outchan
163   
164 let return_all_rdf_uris classs outchan =
165   return_all_foo_uris "allrdfuris" (Http_getter.getallrdfuris classs) outchan
166
167 let return_ls xmluri fmt outchan =
168   let ls_items = Http_getter.ls xmluri in
169   let buf = Buffer.create 10240 in
170   (match fmt with
171   | `Text ->
172       List.iter
173         (function
174           | Ls_section dir -> bprintf buf "dir, %s\n" dir
175           | Ls_object obj ->
176               bprintf buf "object, %s, <%s,%s,%s,%s>\n"
177               obj.uri (if obj.ann then "YES" else "NO")
178               (string_of_ls_flag obj.types)
179               (string_of_ls_flag obj.body)
180               (string_of_ls_flag obj.proof_tree))
181         ls_items
182   | `Xml ->
183       Buffer.add_string buf "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
184       bprintf buf "<!DOCTYPE ls SYSTEM \"%s/getdtd?uri=ls.dtd\">\n"
185         (Lazy.force Http_getter_env.my_own_url);
186       Buffer.add_string buf "<ls>\n";
187       List.iter
188         (function
189           | Ls_section dir -> bprintf buf "<section>%s</section>\n" dir
190           | Ls_object obj ->
191               bprintf buf
192 "<object name=\"%s\">
193 \t<ann value=\"%s\" />
194 \t<types value=\"%s\" />
195 \t<body value=\"%s\" />
196 \t<proof_tree value=\"%s\" />
197 </object>
198 "
199               obj.uri (if obj.ann then "YES" else "NO")
200               (string_of_ls_flag obj.types)
201               (string_of_ls_flag obj.body)
202               (string_of_ls_flag obj.proof_tree))
203         ls_items;
204       Buffer.add_string buf "</ls>\n");
205   let body = Buffer.contents buf in
206   Http_daemon.respond
207     ~headers:(("Content-Type", "text/plain") :: common_headers)
208     ~body outchan
209
210 let return_help outchan = return_html_raw (Http_getter.help ()) outchan
211
212 let return_resolve uri outchan =
213   try
214     return_xml_raw
215       (sprintf "<url value=\"%s\" />\n" (Http_getter.resolve uri))
216       outchan
217   with Unresolvable_URI uri ->
218     return_xml_raw "<unresolved />\n" outchan
219
220 let return_list_servers outchan =
221   return_html_raw
222     (sprintf "<html><body><table>\n%s\n</table></body></html>"
223       (String.concat "\n"
224         (List.map
225           (fun (pos, server) ->
226             sprintf "<tr><td>%d</td><td>%s</td></tr>" pos server)
227           (Http_getter.list_servers ()))))
228     outchan
229
230 let log_failure msg = Http_getter_logger.log ("Request not fulfilled: " ^ msg)
231
232   (** given an action (i.e. a function which expects a logger and do something
233    * using it as a logger), perform it sending its output incrementally to the
234    * given output channel. Response is sent embedded in an HTML document.
235    * Channel is closed afterwards. *)
236 let send_log_to ?prepend action outchan =
237   Http_daemon.send_basic_headers ~code:200 outchan;
238   Http_daemon.send_header "Content-Type" "text/html" outchan;
239   Http_daemon.send_CRLF outchan;
240   output_string outchan "<html><body>\n"; flush outchan;
241   (match prepend with
242   | None -> ()
243   | Some text -> output_string outchan text; flush outchan);
244   let logger tag =
245     output_string outchan (HelmLogger.html_of_html_tag tag);
246     flush outchan
247   in
248   action logger;
249   output_string outchan "\n</body></html>";
250   close_out outchan
251
252   (* thread action *)
253
254 let callback (req: Http_types.request) outchan =
255   try
256     Http_getter_logger.log ("Connection from " ^ req#clientAddr);
257     Http_getter_logger.log ("Received request: " ^ req#path);
258     (match req#path with
259     | "/help" -> return_help outchan
260     | "/getxml" ->
261         let uri = req#param "uri" in
262         Http_getter_cache.respond_xml ~url:(Http_getter.resolve uri) ~uri
263           ~enc:(parse_enc req) ~patch:(parse_patch req) outchan
264     | "/getxslt" ->
265         Http_getter_cache.respond_xsl
266           ~url:(Http_getter.resolve (req#param "uri"))
267           ~patch:(parse_patch req) outchan
268     | "/getdtd" ->
269         Http_getter_cache.respond_dtd ~patch:(parse_patch req)
270           ~url:(sprintf "%s/%s"
271             (Helm_registry.get "getter.dtd_dir") (req#param "uri"))
272           outchan
273     | "/resolve" -> return_resolve (req#param "uri") outchan
274     | "/register" ->
275         Http_getter.register ~uri:(req#param "uri") ~url:(req#param "url");
276         return_html_msg "Register done" outchan
277     | "/clean_cache" ->
278         Http_getter.clean_cache ();
279         return_html_msg "Done." outchan
280     | "/update" ->
281         Http_getter_env.reload (); (* reload servers list from servers file *)
282         send_log_to (fun logger -> Http_getter.update ~logger ()) outchan
283     | "/list_servers" -> return_list_servers outchan
284     | "/add_server" ->
285         let name = req#param "url" in
286         let position = parse_position req in
287         let prepend =
288           sprintf "Added server %s in position %d)<br />\n" name position
289         in
290         send_log_to ~prepend
291           (fun logger -> Http_getter.add_server ~logger ~position name) outchan
292     | "/remove_server" ->
293         let position = parse_position req in
294         if not (Http_getter.has_server position) then
295           raise (Bad_request (sprintf "no server with position %d" position))
296         else
297           let prepend =
298             sprintf "Removed server at position %d<br />\n" position
299           in
300           send_log_to ~prepend
301             (fun logger -> Http_getter.remove_server ~logger position) outchan
302     | "/getalluris" ->
303        return_all_xml_uris (parse_output_format "getalluris" req) outchan
304     | "/getallrdfuris" -> return_all_rdf_uris (parse_rdf_class req) outchan
305     | "/ls" ->
306        return_ls (parse_ls_uri req) (parse_output_format "ls" req) outchan
307     | "/getempty" ->
308         Http_daemon.respond ~body:Http_getter_const.empty_xml outchan
309     | invalid_request ->
310         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
311     Http_getter_logger.log "Done!\n"
312   with
313   | Http_types.Param_not_found attr_name ->
314       let msg = sprintf "Parameter '%s' is missing" attr_name in
315       log_failure msg;
316       return_400 msg outchan
317   | Bad_request msg ->
318       log_failure msg;
319       return_html_error msg outchan
320   | Internal_error msg ->
321       log_failure msg;
322       return_html_internal_error msg outchan
323   | Shell.Subprocess_error l ->
324       let msgs =
325         List.map
326           (fun (cmd, code) ->
327             sprintf "Command '%s' returned %s" cmd (string_of_proc_status code))
328           l
329       in
330       log_failure (String.concat ", " msgs);
331       return_html_internal_error (String.concat "<br />\n" msgs) outchan
332   | exc ->
333       let msg = "Uncaught exception: " ^ (Printexc.to_string exc) in
334       log_failure msg;
335       return_html_error msg outchan
336
337     (* Main *)
338
339 let main () =
340   Helm_registry.load_from configuration_file;
341   Http_getter_logger.set_log_level
342     (Helm_registry.get_opt_default Helm_registry.get_int 1 "getter.log_level");
343   Http_getter_logger.set_log_file
344     (Helm_registry.get_opt Helm_registry.get_string "getter.log_file");
345   Http_getter_env.reload ();
346   print_string (Http_getter_env.env_to_string ());
347   flush stdout;
348   let batch_update =
349     try Sys.argv.(1) = "-update" with Invalid_argument _ -> false
350   in
351   if batch_update then  (* batch mode: performs update and exit *)
352     Http_getter.update ~logger:Http_getter.stdout_logger ()
353   else begin            (* daemon mode: start http daemon *)
354     at_exit Http_getter.close_maps;
355     Sys.catch_break true;
356     try
357       Http_daemon.start' ~mode:`Thread
358         ~timeout:(Some 600) ~port:(Helm_registry.get_int "getter.port")
359         callback
360     with Sys.Break -> ()  (* 'close_maps' already registered with 'at_exit' *)
361   end
362
363 let _ = main ()
364