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