]> matita.cs.unibo.it Git - helm.git/blob - helm/http_getter/http_getter.ml
- fixed helm web page url and copyright notice
[helm.git] / helm / http_getter / http_getter.ml
1 (*
2  * Copyright (C) 2003:
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 Http_getter_common;;
30 open Http_getter_misc;;
31 open Http_getter_types;;
32 open Http_getter_debugger;;
33 open Printf;;
34
35   (* constants *)
36
37 let common_headers = [
38   "Cache-Control", "no-cache";
39   "Pragma", "no-cache";
40   "Expires", "0"
41 ]
42
43   (* HTTP queries argument parsing *)
44
45 let parse_enc (req: Http_types.request) =
46   try
47     (match req#param "format" with
48     | "normal" -> Enc_normal
49     | "gz" -> Enc_gzipped
50     | s -> raise (Http_getter_bad_request ("Invalid format: " ^ s)))
51   with Http_types.Param_not_found _ -> Enc_normal
52 ;;
53 let parse_patch (req: Http_types.request) =
54   match req#param "patch_dtd" with
55   | s when String.lowercase s = "yes" -> true
56   | s when String.lowercase s = "no" -> false
57   | s -> raise (Http_getter_bad_request ("Invalid patch_dtd value: " ^ s))
58 ;;
59 let parse_output_format (req: Http_types.request) =
60   match req#param "format" with
61   | s when String.lowercase s = "txt" -> Fmt_text
62   | s when String.lowercase s = "xml" -> Fmt_xml
63   | s -> raise (Http_getter_bad_request ("Invalid /ls format: " ^ s))
64 ;;
65 let parse_ls_uri =
66   let parse_ls_RE = Pcre.regexp "^(\\w+):(.*)$" in
67   let trailing_slash_RE = Pcre.regexp "/+$" in
68   fun (req: Http_types.request) ->
69     let baseuri = req#param "baseuri" in
70     let subs =
71       Pcre.extract ~rex:parse_ls_RE
72         (Pcre.replace ~rex:trailing_slash_RE  baseuri)
73     in
74     match (subs.(1), subs.(2)) with
75     | "cic", uri -> Cic uri
76     | "theory", uri -> Theory uri
77     | _ -> raise (Http_getter_bad_request ("Invalid /ls baseuri: " ^ baseuri))
78 ;;
79
80   (* global maps, shared by all threads *)
81
82 let xml_map = new Http_getter_map.map Http_getter_env.xml_dbm in
83 let rdf_map = new Http_getter_map.map Http_getter_env.rdf_dbm in
84 let xsl_map = new Http_getter_map.map Http_getter_env.xsl_dbm in
85
86 let save_maps () = xml_map#close; rdf_map#close; xsl_map#close in
87 let map_of_uri = function
88   | uri when is_xml_uri uri -> xml_map
89   | uri when is_rdf_uri uri -> rdf_map
90   | uri when is_xsl_uri uri -> xsl_map
91   | uri -> raise (Http_getter_unresolvable_URI uri)
92 in
93 let resolve uri =
94   try
95     (map_of_uri uri)#resolve uri
96   with Http_getter_map.Key_not_found _ ->
97     raise (Http_getter_unresolvable_URI uri)
98 in
99 let register uri =  (map_of_uri uri )#add uri in
100 let return_all_foo_uris map doctype filter outchan =
101   (** return all URIs contained in 'map' which satisfy predicate 'filter'; URIs
102   are written in an XMLish format ('doctype' is the XML doctype) onto 'outchan'
103   *)
104   Http_daemon.send_basic_headers ~code:200 outchan;
105   Http_daemon.send_header "Content-Type" "text/xml" outchan;
106   Http_daemon.send_headers common_headers outchan;
107   Http_daemon.send_CRLF outchan;
108   output_string
109     outchan
110     (sprintf
111 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
112 <!DOCTYPE %s SYSTEM \"%s/getdtd?uri=%s.dtd\">
113
114 <%s>
115 "
116       doctype
117       Http_getter_env.my_own_url
118       doctype
119       doctype);
120   map#iter
121     (fun uri _ ->
122       if filter uri then
123         output_string outchan (sprintf "\t<uri value=\"%s\" />\n" uri));
124   output_string outchan (sprintf "</%s>\n" doctype)
125 in
126 let return_all_xml_uris = return_all_foo_uris xml_map "alluris" in
127 let return_all_rdf_uris = return_all_foo_uris rdf_map "allrdfuris" in
128 let return_ls =
129   let (++) (oldann, oldtypes, oldbody) (newann, newtypes, newbody) =
130     ((if newann   > oldann    then newann   else oldann),
131      (if newtypes > oldtypes  then newtypes else oldtypes),
132      (if newbody > oldbody    then newbody  else oldbody))
133    in
134   let basepart_RE =
135     Pcre.regexp "^([^.]*\\.[^.]*)((\\.body)|(\\.types))?(\\.ann)?"
136   in
137   let (types_RE, types_ann_RE, body_RE, body_ann_RE) =
138     (Pcre.regexp "\\.types", Pcre.regexp "\\.types.ann",
139      Pcre.regexp "\\.body", Pcre.regexp "\\.body.ann")
140   in
141   let (slash_RE, til_slash_RE, no_slashes_RE) =
142     (Pcre.regexp "/", Pcre.regexp "^.*/", Pcre.regexp "^[^/]*$")
143   in
144   fun lsuri fmt outchan ->
145     let pat =
146       "^" ^
147       (match lsuri with Cic p -> ("cic:" ^ p) | Theory p -> ("theory:" ^ p))
148     in
149     let (dir_RE, obj_RE) =
150       (Pcre.regexp (pat ^ "/"), Pcre.regexp (pat ^ "(\\.|$)"))
151     in
152     let dirs = ref StringSet.empty in
153     let objs = Hashtbl.create 17 in
154     let store_dir d =
155       dirs := StringSet.add (List.hd (Pcre.split ~rex:slash_RE d)) !dirs
156     in
157     let store_obj o =
158       let basepart = Pcre.replace ~rex:basepart_RE ~templ:"$1" o in
159       let oldflags =
160         try
161           Hashtbl.find objs basepart
162         with Not_found -> (false, No, No) (* no ann, no types no body *)
163       in
164       let newflags =
165         match o with
166         | s when Pcre.pmatch ~rex:types_RE s     -> (false, Yes, No)
167         | s when Pcre.pmatch ~rex:types_ann_RE s -> (true,  Ann, No)
168         | s when Pcre.pmatch ~rex:body_RE s      -> (false, No,  Yes)
169         | s when Pcre.pmatch ~rex:body_ann_RE s  -> (true,  No,  Ann)
170         | s -> (false, No, No)
171       in
172       Hashtbl.replace objs basepart (oldflags ++ newflags)
173     in
174     xml_map#iter  (* BLEARGH Dbm module lacks support for fold-like functions *)
175       (fun key _ ->
176         match key with
177         | uri when Pcre.pmatch ~rex:dir_RE uri ->  (* directory hit *)
178             let localpart = Pcre.replace ~rex:dir_RE uri in
179             if Pcre.pmatch ~rex:no_slashes_RE localpart then
180               store_obj localpart
181             else
182               store_dir localpart
183         | uri when Pcre.pmatch ~rex:obj_RE  uri ->  (* file hit *)
184             store_obj (Pcre.replace ~rex:til_slash_RE uri)
185         | uri -> () (* miss *));
186     match fmt with
187     | Fmt_text ->
188         let body =
189           (List.fold_left
190             (fun s d -> sprintf "%sdir, %s\n" s d) ""
191             (StringSet.elements !dirs)) ^
192           (Http_getter_misc.hashtbl_sorted_fold
193             (fun uri (annflag, typesflag, bodyflag) cont ->
194               sprintf "%sobject, %s, <%s,%s,%s>\n"
195                 cont uri (if annflag then "YES" else "NO")
196                 (string_of_ls_flag typesflag) (string_of_ls_flag bodyflag))
197             objs "")
198         in
199         Http_daemon.respond
200           ~headers:(("Content-Type", "text/plain") :: common_headers)
201           ~body outchan
202     | Fmt_xml ->
203         let body =
204           sprintf
205 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
206 <!DOCTYPE ls SYSTEM \"%s/getdtd?uri=ls.dtd\">
207
208 <ls>
209 %s
210 </ls>
211 "
212             Http_getter_env.my_own_url
213             ("\n" ^
214             (String.concat
215               "\n"
216               (List.map
217                 (fun d -> "<section>" ^ d ^ "</section>")
218                 (StringSet.elements !dirs))) ^ "\n" ^
219             (Http_getter_misc.hashtbl_sorted_fold
220               (fun uri (annflag, typesflag, bodyflag) cont ->
221                 sprintf
222 "%s<object name=\"%s\">
223 \t<ann value=\"%s\" />
224 \t<types value=\"%s\" />
225 \t<body value=\"%s\" />
226 </object>
227 "
228                   cont uri (if annflag then "YES" else "NO")
229                   (string_of_ls_flag typesflag)
230                   (string_of_ls_flag bodyflag))
231               objs ""))
232         in
233         Http_daemon.respond
234           ~headers:(("Content-Type", "text/xml") :: common_headers)
235           ~body outchan
236 in
237 let (index_line_sep_RE, index_sep_RE, trailing_types_RE,
238     heading_cic_RE, heading_theory_RE,
239     heading_rdf_cic_RE, heading_rdf_theory_RE) =
240   (Pcre.regexp "[ \t]+", Pcre.regexp "\n+", Pcre.regexp "\\.types$",
241   Pcre.regexp "^cic:", Pcre.regexp "^theory:",
242   Pcre.regexp "^helm:rdf.*//cic:", Pcre.regexp "^helm:rdf.*//theory:")
243 in
244 let update_from_server logmsg server_url = (* use global maps *)
245   debug_print ("Updating information from " ^ server_url);
246   let xml_url_of_uri = function
247       (* TODO missing sanity checks on server_url, e.g. it can contains $1 *)
248     | uri when (Pcre.pmatch ~rex:heading_cic_RE uri) ->
249         Pcre.replace ~rex:heading_cic_RE ~templ:server_url uri
250     | uri when (Pcre.pmatch ~rex:heading_theory_RE uri) ->
251         Pcre.replace ~rex:heading_theory_RE ~templ:server_url uri
252     | uri -> raise (Http_getter_invalid_URI uri)
253   in
254   let rdf_url_of_uri = function (* TODO as above *)
255     | uri when (Pcre.pmatch ~rex:heading_rdf_cic_RE uri) ->
256         Pcre.replace ~rex:heading_rdf_cic_RE ~templ:server_url uri
257     | uri when (Pcre.pmatch ~rex:heading_rdf_theory_RE uri) ->
258         Pcre.replace ~rex:heading_rdf_theory_RE ~templ:server_url uri
259     | uri -> raise (Http_getter_invalid_URI uri)
260   in
261   let log = ref (logmsg ^ "Processing server: " ^ server_url ^ "<br />\n") in
262   let (xml_index, rdf_index, xsl_index) =
263     (* TODO keeps index in memory, is better to keep them on temp files? *)
264     (http_get (server_url ^ "/" ^ Http_getter_env.xml_index),
265      http_get (server_url ^ "/" ^ Http_getter_env.rdf_index),
266      http_get (server_url ^ "/" ^ Http_getter_env.xsl_index))
267   in
268   if (xml_index = None && rdf_index = None && xsl_index = None) then
269     debug_print (sprintf "Warning: useless server %s" server_url);
270   (match xml_index with
271   | Some xml_index ->
272       (log := !log ^ "Updating XML db ...<br />\n";
273       List.iter
274         (fun l ->
275           try
276             (match Pcre.split ~rex:index_line_sep_RE l with
277             | [uri; "gz"] -> xml_map#add uri ((xml_url_of_uri uri) ^ ".xml.gz")
278             | [uri] -> xml_map#add uri ((xml_url_of_uri uri) ^ ".xml")
279             | _ -> log := !log ^ "Ignoring invalid line: " ^ l ^ "<br />\n")
280           with Http_getter_invalid_URI uri ->
281             log := !log ^ "Ignoring invalid XML URI: " ^ uri ^ "<br />\n")
282         (Pcre.split ~rex:index_sep_RE xml_index)) (* xml_index lines *)
283   | None -> ());
284   (match rdf_index with
285   | Some rdf_index ->
286       (log := !log ^ "Updating RDF db ...<br />\n";
287       List.iter
288         (fun l ->
289           try
290             (match Pcre.split ~rex:index_line_sep_RE l with
291             | [uri; "gz"] -> rdf_map#add uri ((rdf_url_of_uri uri) ^ ".xml.gz")
292             | [uri] -> rdf_map#add uri ((rdf_url_of_uri uri) ^ ".xml")
293             | _ -> log := !log ^ "Ignoring invalid line: " ^ l ^ "<br />\n")
294           with Http_getter_invalid_URI uri ->
295             log := !log ^ "Ignoring invalid RDF URI: " ^ uri ^ "<br />\n")
296         (Pcre.split ~rex:index_sep_RE rdf_index)) (* rdf_index lines *)
297   | None -> ());
298   (match xsl_index with
299   | Some xsl_index ->
300       (log := !log ^ "Updating XSLT db ...<br />\n";
301       List.iter
302         (fun l -> xsl_map#add l (server_url ^ "/" ^ l))
303         (Pcre.split ~rex:index_sep_RE xsl_index);
304       log := !log ^ "All done!<br />\n")
305   | None -> ());
306   debug_print "done with this server";
307   !log
308 in
309
310   (* thread action *)
311
312 let callback (req: Http_types.request) outchan =
313   try
314     debug_print ("Connection from " ^ req#clientAddr);
315     debug_print ("Received request: " ^ req#path);
316     (match req#path with
317     | "/help" -> return_html_msg Http_getter_const.usage_string outchan
318     | "/getxml" | "/getxslt" | "/getdtd" | "/resolve" | "/register" ->
319         (let uri = req#param "uri" in  (* common parameter *)
320         match req#path with
321         | "/getxml" ->
322             let enc = parse_enc req in
323             let patch =
324               try parse_patch req with Http_types.Param_not_found _ -> true
325             in
326             Http_getter_cache.respond_xml
327               ~url:(resolve uri) ~uri ~enc ~patch outchan
328         | "/getxslt" ->
329             let patch =
330               try parse_patch req with Http_types.Param_not_found _ -> true
331             in
332             Http_getter_cache.respond_xsl ~url:(resolve uri) ~patch outchan
333         | "/getdtd" ->
334             let patch =
335               try parse_patch req with Http_types.Param_not_found _ -> true
336             in
337             Http_getter_cache.respond_dtd
338               ~patch ~url:(Http_getter_env.dtd_dir ^ "/" ^ uri) outchan
339         | "/resolve" ->
340             (try
341               return_xml_msg
342                 (sprintf "<url value=\"%s\" />\n" (resolve uri))
343                 outchan
344             with Http_getter_unresolvable_URI uri ->
345               return_xml_msg "<unresolved />\n" outchan)
346         | "/register" ->
347             let url = req#param "url" in
348             register uri url;
349             return_html_msg "Register done" outchan
350         | _ -> assert false)
351     | "/update" ->
352         (Http_getter_env.reload (); (* reload servers list from servers file *)
353         xml_map#clear; rdf_map#clear; xsl_map#clear;
354         let log =
355           List.fold_left
356             update_from_server
357             ""  (* initial logmsg: empty *)
358               (* reverse order: 1st server is the most important one *)
359             (List.rev !Http_getter_env.servers)
360         in
361         xml_map#sync; rdf_map#sync; xsl_map#sync;
362         return_html_msg log outchan)
363     | "/getalluris" ->
364         return_all_xml_uris
365           (fun uri ->
366             (Pcre.pmatch ~rex:heading_cic_RE uri) &&
367             not (Pcre.pmatch ~rex:trailing_types_RE uri))
368           outchan
369     | "/getallrdfuris" ->
370         (let classs = req#param "class" in
371         try
372           let filter =
373             let base = "^helm:rdf:www\\.cs\\.unibo\\.it/helm/rdf/" in
374             match classs with
375             | ("forward" as c) | ("backward" as c) ->
376                 (fun uri -> Pcre.pmatch ~pat:(base ^ c) uri)
377             | c -> raise (Http_getter_invalid_RDF_class c)
378           in
379           return_all_rdf_uris filter outchan
380         with Http_getter_invalid_RDF_class c ->
381           raise (Http_getter_bad_request ("Invalid RDF class: " ^ c)))
382     | "/ls" -> return_ls (parse_ls_uri req) (parse_output_format req) outchan
383     | "/getempty" ->
384         Http_daemon.respond ~body:Http_getter_const.empty_xml outchan
385     | invalid_request ->
386         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
387     debug_print "Done!\n"
388   with
389   | Http_types.Param_not_found attr_name ->
390       return_400 (sprintf "Parameter '%s' is missing" attr_name) outchan
391   | Http_getter_bad_request msg -> return_html_error msg outchan
392   | Http_getter_internal_error msg -> return_html_internal_error msg outchan
393   | Shell.Subprocess_error l ->
394       return_html_internal_error
395         (String.concat "<br />\n"
396           (List.map
397             (fun (cmd, code) ->
398               sprintf "Command '%s' returned %s"
399                 cmd (string_of_proc_status code))
400             l))
401         outchan
402   | exc ->
403       return_html_error
404         ("Uncaught exception: " ^ (Printexc.to_string exc))
405         outchan
406 in
407
408     (* daemon initialization *)
409
410 let main () =
411   Http_getter_env.dump_env ();
412   Unix.putenv "http_proxy" "";
413   at_exit save_maps;
414   Sys.catch_break true;
415   try
416     Http_daemon.start'
417       ~timeout:(Some 600) ~port:Http_getter_env.port ~mode:`Thread callback
418   with Sys.Break -> ()  (* 'save_maps' already registered with 'at_exit' *)
419 in
420
421 main ()
422