]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitadaemon.ml
b9aed4be8666891b006324c680760485b47feb91
[helm.git] / matitaB / matita / matitadaemon.ml
1 open Printf;;
2 open Http_types;;
3
4 module Stack = Continuationals.Stack
5
6 let rt_path () = Helm_registry.get "matita.rt_base_dir" 
7
8 let utf8_length = Netconversion.ustring_length `Enc_utf8
9
10 let utf8_parsed_text s floc =
11   let start, stop = HExtlib.loc_of_floc floc in
12   let len = stop - start in
13   let res = Netconversion.ustring_sub `Enc_utf8 start len s in
14   res, String.length res
15
16 (*** from matitaScript.ml ***)
17 (* let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$" *)
18
19 let eval_statement include_paths (* (buffer : GText.buffer) *) status (* script *)
20  statement
21 =
22   let ast,unparsed_text =
23     match statement with
24     | `Raw text ->
25         (* if Pcre.pmatch ~rex:only_dust_RE text then raise Margin; *)
26         let strm =
27          GrafiteParser.parsable_statement status
28           (Ulexing.from_utf8_string text) in
29         let ast = MatitaEngine.get_ast status include_paths strm in
30          ast, text
31     | `Ast (st, text) -> st, text
32   in
33   let floc = match ast with
34   | GrafiteAst.Executable (loc, _)
35   | GrafiteAst.Comment (loc, _) -> loc in
36   
37   let _,lend = HExtlib.loc_of_floc floc in 
38   let parsed_text, _parsed_text_len = 
39     utf8_parsed_text unparsed_text (HExtlib.floc_of_loc (0,lend)) in
40   let byte_parsed_text_len = String.length parsed_text in
41   let unparsed_txt' = 
42     String.sub unparsed_text byte_parsed_text_len 
43       (String.length unparsed_text - byte_parsed_text_len)
44   in
45   
46   let status = 
47     MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:false status ("",0,ast)
48   in 
49   (status, parsed_text, unparsed_txt'),"",(*parsed_text_len*)
50     utf8_length parsed_text
51
52 let sequent_size = ref 40;;
53
54 let include_paths = ref [];;
55
56 (* <metasenv>
57  *   <meta number="...">
58  *     <metaname>...</metaname>
59  *     <goal>...</goal>
60  *   </meta>
61  *
62  *   ...
63  * </metasenv> *)
64 let output_status s =
65   let _,_,metasenv,subst,_ = s#obj in
66   let render_switch = function 
67   | Stack.Open i -> "?" ^ (string_of_int i) 
68   | Stack.Closed i -> "<S>?" ^ (string_of_int i) ^ "</S>"
69   in
70   let int_of_switch = function
71   | Stack.Open i | Stack.Closed i -> i
72   in
73   let sequent = function
74   | Stack.Open i ->
75       let meta = List.assoc i metasenv in
76       snd (ApplyTransformation.ntxt_of_cic_sequent 
77         ~metasenv ~subst ~map_unicode_to_tex:false !sequent_size s (i,meta))
78   | Stack.Closed _ -> "This goal has already been closed."
79   in
80   let render_sequent is_loc acc depth tag (pos,sw) =
81     let metano = int_of_switch sw in
82     let markup = 
83       if is_loc then
84         (match depth, pos with
85          | 0, 0 -> "<B>" ^ (render_switch sw) ^ "</B>"
86          | 0, _ -> 
87             Printf.sprintf "<B>|<SUB>%d</SUB>: %s</B>" pos (render_switch sw)
88          | 1, pos when Stack.head_tag s#stack = `BranchTag ->
89              Printf.sprintf "|<SUB>%d</SUB> : %s" pos (render_switch sw)
90          | _ -> render_switch sw)
91       else render_switch sw
92     in
93     prerr_endline "pippo1";
94     let markup = 
95       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () markup in
96     let markup = "<metaname>" ^ markup ^ "</metaname>" in
97     prerr_endline "pippo2";
98     let sequent =
99       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () (sequent sw)
100     in      
101     let txt0 = "<goal>" ^ sequent ^ "</goal>" in
102     "<meta number=\"" ^ (string_of_int metano) ^ "\">" ^ markup ^
103     txt0 ^ "</meta>" ^ acc
104   in
105   let res = "<metasenv>" ^
106     (Stack.fold 
107       ~env:(render_sequent true) ~cont:(render_sequent false) 
108       ~todo:(render_sequent false) "" s#stack) ^
109     "</metasenv>"
110   in 
111   prerr_endline ("sending metasenv:\n" ^ res); res
112 ;;
113
114 (* let html_of_status s =
115   let _,_,metasenv,subst,_ = s#obj in
116   let txt = List.fold_left 
117     (fun acc (nmeta,_ as meta) ->
118        let txt0 = snd (ApplyTransformation.ntxt_of_cic_sequent 
119          ~metasenv ~subst ~map_unicode_to_tex:false 80 s meta)
120        in
121        prerr_endline ("### txt0 = " ^ txt0);
122       ("<B>Goal ?" ^ (string_of_int nmeta) ^ "</B>\n" ^ txt0)::acc)
123     [] metasenv
124   in
125   String.concat "\n\n" txt
126 ;; *)
127
128 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*";;
129
130 let first_line s =
131   let s = Pcre.replace ~rex:heading_nl_RE s in
132   try
133     let nl_pos = String.index s '\n' in
134     String.sub s 0 nl_pos
135   with Not_found -> s
136 ;;
137
138 let read_file fname =
139   let chan = open_in fname in
140   let lines = ref [] in
141   (try
142      while true do
143        lines := input_line chan :: !lines
144      done;
145    with End_of_file -> close_in chan);
146   String.concat "\n" (List.rev !lines)
147 ;;
148
149 let load_index outchan =
150   let s = read_file "index.html" in
151   Http_daemon.respond ~headers:["Content-Type", "text/html"] ~code:(`Code 200) ~body:s outchan
152 ;;
153
154 let load_doc filename outchan =
155   let s = read_file filename in
156   let is_png = 
157     try String.sub filename (String.length filename - 4) 4 = ".png"
158     with Invalid_argument _ -> false
159   in
160   let contenttype = if is_png then "image/png" else "text/html" in
161   Http_daemon.respond ~headers:["Content-Type", contenttype] ~code:(`Code 200) ~body:s outchan
162 ;;
163
164 let retrieve (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
165   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
166   let env = cgi#environment in
167   (try 
168     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
169     let sid = HExtlib.unopt sid in
170     cgi # set_header 
171       ~cache:`No_cache 
172       ~content_type:"text/xml; charset=\"utf-8\""
173       ();
174     let filename = cgi # argument_value "file" in
175     prerr_endline ("reading file " ^ filename);
176     let body = 
177       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () 
178         (read_file filename) in
179     prerr_endline ("sending:\nBEGIN\n" ^ body ^ "\nEND");
180     let body = "<file>" ^ body ^ "</file>" in
181     let baseuri, incpaths = 
182       try 
183         let root, baseuri, _fname, _tgt = 
184           Librarian.baseuri_of_script ~include_paths:[] filename in 
185         let includes =
186          try
187           Str.split (Str.regexp " ") 
188            (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
189          with Not_found -> []
190         in
191         let rc = root :: includes in
192          List.iter (HLog.debug) rc; baseuri, rc
193        with 
194          Librarian.NoRootFor _ | Librarian.FileNotFound _ -> "",[] in
195     include_paths := incpaths;
196     let status = MatitaAuthentication.get_status sid in
197     MatitaAuthentication.set_status sid (status#set_baseuri baseuri);
198     cgi#out_channel#output_string body;
199   with
200   | Not_found _ -> 
201     cgi # set_header
202       ~status:`Internal_server_error
203       ~cache:`No_cache 
204       ~content_type:"text/xml; charset=\"utf-8\""
205       ());
206   cgi#out_channel#commit_work()
207 ;;
208
209 let advance0 sid text =
210   let status = MatitaAuthentication.get_status sid in
211   let history = MatitaAuthentication.get_history sid in
212   let (st,new_statements,new_unparsed),(* newtext TODO *) _,parsed_len =
213        (* try *)
214          eval_statement !include_paths (*buffer*) status (`Raw text)
215        (* with End_of_file -> raise Margin *)
216      in
217   MatitaAuthentication.set_status sid st;
218   MatitaAuthentication.set_history sid (st::history);
219   parsed_len, new_unparsed, st
220
221 let register (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
222   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
223   let env = cgi#environment in
224   
225   assert (cgi#arguments <> []);
226   let uid = cgi#argument_value "userid" in
227   let userpw = cgi#argument_value "password" in
228   (try 
229     MatitaAuthentication.add_user uid userpw;
230     env#set_output_header_field "Location" "/index.html"
231    with
232    | MatitaAuthentication.UsernameCollision _ ->
233       cgi#set_header
234        ~cache:`No_cache 
235        ~content_type:"text/html; charset=\"utf-8\""
236        ();
237      cgi#out_channel#output_string
238       "<html><head></head><body>Error: User id collision!</body></html>"
239    | MatitaFilesystem.SvnError msg ->
240       cgi#set_header
241        ~cache:`No_cache 
242        ~content_type:"text/html; charset=\"utf-8\""
243        ();
244      cgi#out_channel#output_string
245       ("<html><head></head><body><p>Error: Svn checkout failed!<p><p><textarea>"
246        ^ msg ^ "</textarea></p></body></html>"));
247   cgi#out_channel#commit_work()
248 ;;
249
250 let login (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
251   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
252   let env = cgi#environment in
253   
254   assert (cgi#arguments <> []);
255   let uid = cgi#argument_value "userid" in
256   let userpw = cgi#argument_value "password" in
257   let pw,_ = MatitaAuthentication.lookup_user uid in
258
259   if pw = userpw then
260    begin
261     let _ = MatitaFilesystem.html_of_library uid in
262     let sid = MatitaAuthentication.create_session uid in
263     (* let cookie = Netcgi.Cookie.make "session" (Uuidm.to_string sid) in
264        cgi#set_header ~set_cookies:[cookie] (); *)
265     env#set_output_header_field 
266       "Set-Cookie" ("session=" ^ (Uuidm.to_string sid));
267     env#set_output_header_field "Location" "/index.html"
268    end
269   else
270    begin
271     prerr_endline ("ERROR: received " ^ userpw ^ "but the password is " ^ pw);
272     cgi#set_header
273       ~cache:`No_cache 
274       ~content_type:"text/html; charset=\"utf-8\""
275       ();
276     cgi#out_channel#output_string
277       "<html><head></head><body>Authentication error</body></html>"
278    end;
279     
280   cgi#out_channel#commit_work()
281   
282 ;;
283
284 let logout (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
285   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
286   let env = cgi#environment in
287   (try 
288     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
289     let sid = HExtlib.unopt sid in
290     MatitaAuthentication.logout_user sid;
291     cgi # set_header 
292       ~cache:`No_cache 
293       ~content_type:"text/html; charset=\"utf-8\""
294       ();
295     let text = read_file (rt_path () ^ "/logout.html") in
296     cgi#out_channel#output_string text
297   with
298   | Not_found _ -> 
299     cgi # set_header
300       ~status:`Internal_server_error
301       ~cache:`No_cache 
302       ~content_type:"text/xml; charset=\"utf-8\""
303       ());
304   cgi#out_channel#commit_work()
305 ;;
306
307 (* returns the length of the executed text and an html representation of the
308  * current metasenv*)
309 let advance (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
310   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
311   let env = cgi#environment in
312   (try 
313     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
314     let sid = HExtlib.unopt sid in
315     cgi # set_header 
316       ~cache:`No_cache 
317       ~content_type:"text/xml; charset=\"utf-8\""
318       ();
319     let text = cgi#argument_value "body" in
320     prerr_endline ("body =\n" ^ text);
321     let parsed_len, new_unparsed, new_status = advance0 sid text in
322     let txt = output_status new_status in
323     let body = 
324        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
325        ^ "</response>"
326     in 
327     prerr_endline ("sending advance response:\n" ^ body);
328     cgi#out_channel#output_string body
329   with
330   | Not_found _ -> 
331     cgi # set_header
332       ~status:`Internal_server_error
333       ~cache:`No_cache 
334       ~content_type:"text/xml; charset=\"utf-8\""
335       ());
336   cgi#out_channel#commit_work()
337 ;;
338
339 let gotoBottom (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
340   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
341   let env = cgi#environment in
342   (try 
343     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
344     let sid = HExtlib.unopt sid in
345
346     let rec aux parsed_len text =
347       try
348         prerr_endline ("evaluating: " ^ first_line text);
349         let plen,new_unparsed,_new_status = advance0 sid text in
350         aux (parsed_len+plen) new_unparsed
351       with 
352       | _ -> parsed_len
353     in 
354     cgi # set_header 
355       ~cache:`No_cache 
356       ~content_type:"text/xml; charset=\"utf-8\""
357       ();
358     let text = cgi#argument_value "body" in
359     prerr_endline ("body =\n" ^ text);
360     let parsed_len = aux 0 text in
361     let status = MatitaAuthentication.get_status sid in
362     let txt = output_status status in
363     let body = 
364        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
365        ^ "</response>"
366     in 
367     prerr_endline ("sending goto bottom response:\n" ^ body);
368     cgi#out_channel#output_string body
369    with Not_found -> cgi#set_header ~status:`Internal_server_error 
370       ~cache:`No_cache 
371       ~content_type:"text/xml; charset=\"utf-8\"" ());
372   cgi#out_channel#commit_work() 
373 ;;
374
375 let retract (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
376   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
377   let env = cgi#environment in
378   (try 
379     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
380     let sid = HExtlib.unopt sid in
381     cgi # set_header 
382       ~cache:`No_cache 
383       ~content_type:"text/xml; charset=\"utf-8\""
384       ();
385     let history = MatitaAuthentication.get_history sid in
386     let new_history,new_status =
387        match history with
388          _::(status::_ as history) ->
389           history, status
390       | [_] -> (prerr_endline "singleton";failwith "retract")
391       | _ -> (prerr_endline "nil"; assert false) in
392     NCicLibrary.time_travel new_status;
393     MatitaAuthentication.set_history sid new_history;
394     MatitaAuthentication.set_status sid new_status;
395     prerr_endline ("after retract history.length = " ^ 
396       string_of_int (List.length new_history));
397     let body = output_status new_status in
398     cgi#out_channel#output_string body
399    with _ -> cgi#set_header ~status:`Internal_server_error 
400       ~cache:`No_cache 
401       ~content_type:"text/xml; charset=\"utf-8\"" ());
402   cgi#out_channel#commit_work() 
403 ;;
404
405
406 let viewLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
407   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
408   let env = cgi#environment in
409   
410     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
411     let sid = HExtlib.unopt sid in
412     cgi # set_header 
413       ~cache:`No_cache 
414       ~content_type:"text/xml; charset=\"utf-8\""
415       ();
416     let uid = MatitaAuthentication.user_of_session sid in
417     
418     let html = MatitaFilesystem.html_of_library uid in
419     cgi#out_channel#output_string
420       ("<html><head></head><body>" ^ html ^ "</body></html>");
421   cgi#out_channel#commit_work()
422   
423 ;;
424
425 open Netcgi1_compat.Netcgi_types;;
426
427 (**********************************************************************)
428 (* Create the webserver                                               *)
429 (**********************************************************************)
430
431
432 let start() =
433   let (opt_list, cmdline_cfg) = Netplex_main.args() in
434
435   let use_mt = ref true in
436
437   let opt_list' =
438     [ "-mt", Arg.Set use_mt,
439       "  Use multi-threading instead of multi-processing"
440     ] @ opt_list in
441
442   Arg.parse 
443     opt_list'
444     (fun s -> raise (Arg.Bad ("Don't know what to do with: " ^ s)))
445     "usage: netplex [options]";
446   let parallelizer = 
447     if !use_mt then
448       Netplex_mt.mt()     (* multi-threading *)
449     else
450       Netplex_mp.mp() in  (* multi-processing *)
451 (*
452   let adder =
453     { Nethttpd_services.dyn_handler = (fun _ -> process1);
454       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
455       dyn_uri = None;                 (* not needed *)
456       dyn_translator = (fun _ -> ""); (* not needed *)
457       dyn_accept_all_conditionals = false;
458     } in
459 *)
460   let do_advance =
461     { Nethttpd_services.dyn_handler = (fun _ -> advance);
462       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
463       dyn_uri = None;                 (* not needed *)
464       dyn_translator = (fun _ -> ""); (* not needed *)
465       dyn_accept_all_conditionals = false;
466     } in
467   let do_retract =
468     { Nethttpd_services.dyn_handler = (fun _ -> retract);
469       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
470       dyn_uri = None;                 (* not needed *)
471       dyn_translator = (fun _ -> ""); (* not needed *)
472       dyn_accept_all_conditionals = false;
473     } in
474   let goto_bottom =
475     { Nethttpd_services.dyn_handler = (fun _ -> gotoBottom);
476       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
477       dyn_uri = None;                 (* not needed *)
478       dyn_translator = (fun _ -> ""); (* not needed *)
479       dyn_accept_all_conditionals = false;
480     } in
481   let retrieve =
482     { Nethttpd_services.dyn_handler = (fun _ -> retrieve);
483       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
484       dyn_uri = None;                 (* not needed *)
485       dyn_translator = (fun _ -> ""); (* not needed *)
486       dyn_accept_all_conditionals = false;
487     } in
488   let do_register =
489     { Nethttpd_services.dyn_handler = (fun _ -> register);
490       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
491       dyn_uri = None;                 (* not needed *)
492       dyn_translator = (fun _ -> ""); (* not needed *)
493       dyn_accept_all_conditionals = false;
494     } in
495   let do_login =
496     { Nethttpd_services.dyn_handler = (fun _ -> login);
497       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
498       dyn_uri = None;                 (* not needed *)
499       dyn_translator = (fun _ -> ""); (* not needed *)
500       dyn_accept_all_conditionals = false;
501     } in
502   let do_logout =
503     { Nethttpd_services.dyn_handler = (fun _ -> logout);
504       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
505       dyn_uri = None;                 (* not needed *)
506       dyn_translator = (fun _ -> ""); (* not needed *)
507       dyn_accept_all_conditionals = false;
508     } in 
509   let do_viewlib =
510     { Nethttpd_services.dyn_handler = (fun _ -> viewLib);
511       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
512       dyn_uri = None;                 (* not needed *)
513       dyn_translator = (fun _ -> ""); (* not needed *)
514       dyn_accept_all_conditionals = false;
515     } in 
516   
517   let nethttpd_factory = 
518     Nethttpd_plex.nethttpd_factory
519       ~handlers:[ "advance", do_advance
520                 ; "retract", do_retract
521                 ; "bottom", goto_bottom
522                 ; "open", retrieve 
523                 ; "register", do_register
524                 ; "login", do_login 
525                 ; "logout", do_logout 
526                 ; "viewlib", do_viewlib]
527       () in
528   MatitaInit.initialize_all ();
529   MatitaAuthentication.deserialize ();
530   Netplex_main.startup
531     parallelizer
532     Netplex_log.logger_factories   (* allow all built-in logging styles *)
533     Netplex_workload.workload_manager_factories (* ... all ways of workload management *)
534     [ nethttpd_factory ]           (* make this nethttpd available *)
535     cmdline_cfg
536 ;;
537
538 Sys.set_signal Sys.sigpipe Sys.Signal_ignore;
539 start();;