]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitadaemon.ml
81fa956e1161b87855080b26a7882bb647c57b40
[helm.git] / matitaB / matita / matitadaemon.ml
1 open Printf;;
2 open Http_types;;
3
4 exception Emphasized_error of string
5 exception Ambiguous of string
6
7 module Stack = Continuationals.Stack
8
9 let rt_path () = Helm_registry.get "matita.rt_base_dir" 
10
11 let libdir uid = (rt_path ()) ^ "/users/" ^ uid 
12
13 let utf8_length = Netconversion.ustring_length `Enc_utf8
14
15 let mutex = Mutex.create ();;
16
17 let to_be_committed = ref [];;
18
19 let html_of_matita s =
20   let patt1 = Str.regexp "\005" in
21   let patt2 = Str.regexp "\006" in
22   let patt3 = Str.regexp "<" in
23   let patt4 = Str.regexp ">" in
24   let res = Str.global_replace patt4 "&gt;" s in
25   let res = Str.global_replace patt3 "&lt;" res in
26   let res = Str.global_replace patt2 ">" res in
27   let res = Str.global_replace patt1 "<" res in
28   res
29 ;;
30
31 (* adds a user to the commit queue; concurrent instances possible, so we
32  * enclose the update in a CS
33  *)
34 let add_user_for_commit uid =
35   Mutex.lock mutex;
36   to_be_committed := uid::List.filter (fun x -> x <> uid) !to_be_committed;
37   Mutex.unlock mutex;
38 ;;
39
40 let do_global_commit () =
41   prerr_endline ("to be committed: " ^ String.concat " " !to_be_committed);
42   List.fold_left
43     (fun out u ->
44        let ft = MatitaAuthentication.read_ft u in
45
46        (* first we add new files/dirs to the repository *)
47        (* must take the reverse because svn requires the add to be performed in
48           the correct order
49           (otherwise run with --parents option) *)
50        let to_be_added = List.rev (List.map fst  
51          (List.filter (fun (_,flag) -> flag = MatitaFilesystem.MAdd) ft))
52        in
53        prerr_endline ("@@@ ADDING files: " ^ String.concat ", " to_be_added);
54        let out = 
55          try
56            let newout = MatitaFilesystem.add_files u to_be_added in
57            out ^ "\n" ^ newout
58          with
59          | MatitaFilesystem.SvnError outstr -> 
60              prerr_endline ("ADD OF " ^ u ^ "FAILED:" ^ outstr);
61              out
62        in
63
64        (* now we update the local copy (to merge updates from other users) *)
65        let out = try
66          let files,anomalies,(added,conflict,del,upd,merged) = 
67            MatitaFilesystem.update_user u 
68          in
69          let anomalies = String.concat "\n" anomalies in
70          let details = Printf.sprintf 
71            ("%d new files\n"^^
72             "%d deleted files\n"^^
73             "%d updated files\n"^^
74             "%d merged files\n"^^
75             "%d conflicting files\n\n" ^^
76             "Anomalies:\n%s") added del upd merged conflict anomalies
77          in
78          prerr_endline ("update details:\n" ^ details);
79          MatitaAuthentication.set_file_flag u files;
80          out ^ "\n" ^ details 
81          with
82          | MatitaFilesystem.SvnError outstr -> 
83              prerr_endline ("UPDATE OF " ^ u ^ "FAILED:" ^ outstr);
84              out
85        in
86
87        (* we re-read the file table after updating *)
88        let ft = MatitaAuthentication.read_ft u in
89
90        (* finally we perform the real commit *)
91        let modified = (List.map fst
92          (List.filter (fun (_,flag) -> flag = MatitaFilesystem.MModified) ft))
93        in
94        let to_be_committed = to_be_added @ modified
95        in
96        let out = try
97          let newout = MatitaFilesystem.commit u to_be_committed in
98          out ^ "\n" ^ newout
99          with
100          | MatitaFilesystem.SvnError outstr -> 
101              prerr_endline ("COMMIT OF " ^ u ^ "FAILED:" ^ outstr);
102              out
103        in
104
105        (* call stat to get the final status *)
106        let files, anomalies = MatitaFilesystem.stat_user u in
107        let added,not_added = List.fold_left 
108          (fun (a_acc, na_acc) fname ->
109             if List.mem fname (List.map fst files) then
110                a_acc, fname::na_acc
111             else
112                fname::a_acc, na_acc)
113          ([],[]) to_be_added
114        in
115        let committed,not_committed = List.fold_left 
116          (fun (c_acc, nc_acc) fname ->
117             if List.mem fname (List.map fst files) then
118                c_acc, fname::nc_acc
119             else
120                fname::c_acc, nc_acc)
121          ([],[]) modified
122        in
123        let conflicts = List.map fst (List.filter 
124          (fun (_,f) -> f = Some MatitaFilesystem.MConflict) files)
125        in
126        MatitaAuthentication.set_file_flag u
127          (List.map (fun x -> x, Some MatitaFilesystem.MSynchronized) (added@committed));
128        MatitaAuthentication.set_file_flag u files;
129        out ^ "\n\n" ^ (Printf.sprintf
130         ("COMMIT RESULTS for %s\n" ^^
131          "==============\n" ^^
132          "added and committed (%d of %d): %s\n" ^^
133          "modified and committed (%d of %d): %s\n" ^^
134          "not added: %s\n" ^^
135          "not committed: %s\n" ^^
136          "conflicts: %s\n")
137          u (List.length added) (List.length to_be_added) (String.concat ", " added)
138          (List.length committed) (List.length modified) (String.concat ", " committed)
139          (String.concat ", " not_added)
140          (String.concat ", " not_committed) (String.concat ", " conflicts)))
141
142   (* XXX: at the moment, we don't keep track of the order in which users have 
143      scheduled their commits, but we should, otherwise we will get a 
144      "first come, random served" policy *)
145   "" (* (List.rev !to_be_committed) *) (MatitaAuthentication.get_users ())
146 ;;
147
148 (*** from matitaScript.ml ***)
149 (* let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$" *)
150
151 let eval_statement include_paths (* (buffer : GText.buffer) *) status (* script *)
152  statement
153 =
154   let ast,unparsed_text =
155     match statement with
156     | `Raw text ->
157         (* if Pcre.pmatch ~rex:only_dust_RE text then raise Margin; *)
158         prerr_endline ("raw text = " ^ text);
159         let strm =
160          GrafiteParser.parsable_statement status
161           (Ulexing.from_utf8_string text) in
162         prerr_endline "before get_ast";
163         let ast = MatitaEngine.get_ast status include_paths strm in
164         prerr_endline "after get_ast";
165          ast, text
166     | `Ast (st, text) -> st, text
167   in
168
169   (* do we want to generate a trace? *)
170   let is_auto (l,a) = 
171     not (List.mem_assoc "demod" a || List.mem_assoc "paramod" a ||
172       List.mem_assoc "fast_paramod" a || List.assoc "depth" a = "1" ||
173       l <> None)
174   in
175
176   let get_param a param = 
177      try 
178        Some (param ^ "=" ^ List.assoc param a)
179      with Not_found -> None
180   in
181
182   let floc = match ast with
183   | GrafiteAst.Executable (loc, _)
184   | GrafiteAst.Comment (loc, _) -> loc in
185   
186   let lstart,lend = HExtlib.loc_of_floc floc in 
187   let parsed_text, _parsed_text_len = 
188     HExtlib.utf8_parsed_text unparsed_text (HExtlib.floc_of_loc (0,lend)) in
189   let parsed_text_len = utf8_length parsed_text in
190   let byte_parsed_text_len = String.length parsed_text in
191   let unparsed_txt' = 
192     String.sub unparsed_text byte_parsed_text_len 
193       (String.length unparsed_text - byte_parsed_text_len)
194   in
195   let pre = Netconversion.ustring_sub `Enc_utf8  0 lstart parsed_text in
196
197   let mk_univ trace = 
198     let href r = 
199       Printf.sprintf "\005A href=\"%s\"\006%s\005/A\006"
200         (NReference.string_of_reference r) (NCicPp.r2s status true r)
201     in
202     if trace = [] then "{}"
203     else String.concat ", " 
204       (HExtlib.filter_map (function 
205         | NotationPt.NRef r -> Some (href r) 
206         | _ -> None)
207       trace)
208   in
209   
210   match ast with
211   | GrafiteAst.Executable (_,
212       GrafiteAst.NTactic (_,
213         [GrafiteAst.NAuto (_, (l,a as auto_params))])) when is_auto auto_params
214           ->
215           let l = match l with
216           | None -> None
217           | Some (_,l') -> Some (List.map (fun x -> "",0,x) l')
218           in
219           let trace_ref = ref [] in
220           let status = NnAuto.auto_tac ~params:(l,a) ~trace_ref status in
221           let new_parsed_text = pre ^ (Printf.sprintf 
222             "/\005span class='autotactic'\006%s\005span class='autotrace'\006 trace %s\005/span\006\005/span\006/"
223              (String.concat " " 
224                (List.assoc "depth" a::
225                 HExtlib.filter_map (get_param a) ["width";"size"]))
226              (mk_univ !trace_ref))
227           in
228           (status,new_parsed_text, unparsed_txt'),parsed_text_len
229   | _ ->
230       let status = 
231         MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:false status ("",0,ast)
232       in
233       let new_parsed_text = Ulexing.from_utf8_string parsed_text in
234       let interpr = GrafiteDisambiguate.get_interpr status#disambiguate_db in
235       let outstr = ref "" in
236       ignore (SmallLexer.mk_small_printer interpr outstr new_parsed_text);
237       prerr_endline ("baseuri after advance = " ^ status#baseuri);
238       (* prerr_endline ("parser output: " ^ !outstr); *)
239       (status,!outstr, unparsed_txt'),parsed_text_len
240
241 (*let save_moo status = 
242   let script = MatitaScript.current () in
243   let baseuri = status#baseuri in
244   match script#bos, script#eos with
245   | true, _ -> ()
246   | _, true ->
247      GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
248       status
249   | _ -> clean_current_baseuri status 
250 ;;*)
251     
252 let sequent_size = ref 40;;
253
254 let include_paths = ref [];;
255
256 (* <metasenv>
257  *   <meta number="...">
258  *     <metaname>...</metaname>
259  *     <goal>...</goal>
260  *   </meta>
261  *
262  *   ...
263  * </metasenv> *)
264 let output_status s =
265   let _,_,metasenv,subst,_ = s#obj in
266   let render_switch = function 
267   | Stack.Open i -> "?" ^ (string_of_int i) 
268   | Stack.Closed i -> "<S>?" ^ (string_of_int i) ^ "</S>"
269   in
270   let int_of_switch = function
271   | Stack.Open i | Stack.Closed i -> i
272   in
273   let sequent = function
274   | Stack.Open i ->
275       let meta = List.assoc i metasenv in
276       snd (ApplyTransformation.ntxt_of_cic_sequent 
277         ~metasenv ~subst ~map_unicode_to_tex:false !sequent_size s (i,meta))
278   | Stack.Closed _ -> "This goal has already been closed."
279   in
280   let render_sequent is_loc acc depth tag (pos,sw) =
281     let metano = int_of_switch sw in
282     let markup = 
283       if is_loc then
284         (match depth, pos with
285          | 0, 0 -> "<span class=\"activegoal\">" ^ (render_switch sw) ^ "</span>"
286          | 0, _ -> 
287             Printf.sprintf "<span class=\"activegoal\">|<SUB>%d</SUB>: %s</span>" pos (render_switch sw)
288          | 1, pos when Stack.head_tag s#stack = `BranchTag ->
289              Printf.sprintf "<span class=\"passivegoal\">|<SUB>%d</SUB> : %s</span>" pos (render_switch sw)
290          | _ -> render_switch sw)
291       else render_switch sw
292     in
293     let markup = 
294       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () markup in
295     let markup = "<metaname>" ^ markup ^ "</metaname>" in
296     let sequent =
297       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () (sequent sw)
298     in      
299     let txt0 = "<goal>" ^ sequent ^ "</goal>" in
300     "<meta number=\"" ^ (string_of_int metano) ^ "\">" ^ markup ^
301     txt0 ^ "</meta>" ^ acc
302   in
303   "<metasenv>" ^
304     (Stack.fold 
305       ~env:(render_sequent true) ~cont:(render_sequent false) 
306       ~todo:(render_sequent false) "" s#stack) ^
307     "</metasenv>"
308   (* prerr_endline ("sending metasenv:\n" ^ res); res *)
309 ;;
310
311 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*";;
312
313 let first_line s =
314   let s = Pcre.replace ~rex:heading_nl_RE s in
315   try
316     let nl_pos = String.index s '\n' in
317     String.sub s 0 nl_pos
318   with Not_found -> s
319 ;;
320
321 let read_file fname =
322   let chan = open_in fname in
323   let lines = ref [] in
324   (try
325      while true do
326        lines := input_line chan :: !lines
327      done;
328    with End_of_file -> close_in chan);
329   String.concat "\n" (List.rev !lines)
330 ;;
331
332 let load_index outchan =
333   let s = read_file "index.html" in
334   Http_daemon.respond ~headers:["Content-Type", "text/html"] ~code:(`Code 200) ~body:s outchan
335 ;;
336
337 let load_doc filename outchan =
338   let s = read_file filename in
339   let is_png = 
340     try String.sub filename (String.length filename - 4) 4 = ".png"
341     with Invalid_argument _ -> false
342   in
343   let contenttype = if is_png then "image/png" else "text/html" in
344   Http_daemon.respond ~headers:["Content-Type", contenttype] ~code:(`Code 200) ~body:s outchan
345 ;;
346
347 let retrieve (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
348   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
349   let env = cgi#environment in
350   (try 
351     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
352     let sid = HExtlib.unopt sid in
353     let uid = MatitaAuthentication.user_of_session sid in
354     (*
355     cgi # set_header 
356       ~cache:`No_cache 
357       ~content_type:"text/xml; charset=\"utf-8\""
358       ();
359     *)
360     let filename = libdir uid ^ "/" ^ (cgi # argument_value "file") in
361     (* prerr_endline ("reading file " ^ filename); *)
362     let body = 
363      Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false ()
364         (html_of_matita (read_file filename)) in
365      
366      (*   html_of_matita (read_file filename) in *)
367     (* prerr_endline ("sending:\nBEGIN\n" ^ body ^ "\nEND"); *)
368     let body = "<response><file>" ^ body ^ "</file></response>" in
369     let baseuri, incpaths = 
370       try 
371         let root, baseuri, _fname, _tgt = 
372           Librarian.baseuri_of_script ~include_paths:[] filename in 
373         let includes =
374          try
375           Str.split (Str.regexp " ") 
376            (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
377          with Not_found -> []
378         in
379         let rc = root :: includes in
380          List.iter (HLog.debug) rc; baseuri, rc
381        with 
382          Librarian.NoRootFor _ | Librarian.FileNotFound _ -> "",[] in
383     include_paths := incpaths;
384     let status = (MatitaAuthentication.get_status sid)#set_baseuri baseuri in
385     let history = [status] in
386     MatitaAuthentication.set_status sid status;
387     MatitaAuthentication.set_history sid history;
388     cgi # set_header 
389       ~cache:`No_cache 
390       ~content_type:"text/xml; charset=\"utf-8\""
391       ();
392     cgi#out_channel#output_string body;
393   with
394   | Not_found _ -> 
395     cgi # set_header
396       ~status:`Internal_server_error
397       ~cache:`No_cache 
398       ~content_type:"text/html; charset=\"utf-8\""
399       ());
400   cgi#out_channel#commit_work()
401 ;;
402
403 let advance0 sid text =
404   let status = MatitaAuthentication.get_status sid in
405   let status = status#reset_disambiguate_db () in
406   let (st,new_statements,new_unparsed),parsed_len =
407     try
408     eval_statement !include_paths (*buffer*) status (`Raw text)
409     with
410     | HExtlib.Localized (floc,e) as exn ->
411       let x, y = HExtlib.loc_of_floc floc in
412       let pre = Netconversion.ustring_sub `Enc_utf8  0 x text in
413       let err = Netconversion.ustring_sub `Enc_utf8  x (y-x) text in
414       let post = Netconversion.ustring_sub `Enc_utf8 y 
415          (Netconversion.ustring_length `Enc_utf8 text - y) text in
416       let _,title = MatitaExcPp.to_string exn in
417       (* let title = "" in *)
418       let marked = 
419         pre ^ "\005span class=\"error\" title=\"" ^ title ^ "\"\006" ^ err ^ "\005/span\006" ^ post in
420       let marked = Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false 
421       () (html_of_matita marked) in
422       raise (Emphasized_error marked) 
423     | NTacStatus.Error (s,None) as e ->
424         prerr_endline 
425           ("NTacStatus.Error " ^ (Lazy.force s));
426         raise e
427     | NTacStatus.Error (s,Some exc) as e ->
428         prerr_endline 
429           ("NTacStatus.Error " ^ Lazy.force s ^ " -- " ^ (Printexc.to_string exc));
430         raise e
431     | GrafiteDisambiguate.Ambiguous_input (loc,choices) ->
432       let x,y = HExtlib.loc_of_floc loc in
433       let choice_of_alias = function
434        | GrafiteAst.Ident_alias (_,uri) -> uri, None, uri
435        | GrafiteAst.Number_alias (None,desc)
436        | GrafiteAst.Symbol_alias (_,None,desc) -> "cic:/fakeuri.def(1)", Some desc, desc
437        | GrafiteAst.Number_alias (Some uri,desc)
438        | GrafiteAst.Symbol_alias (_,Some uri,desc) -> uri, Some desc, desc
439       in
440       let tag_of_choice (uri,title,desc) =
441         match title with
442         | None -> Printf.sprintf "<choice href=\"%s\">%s</choice>"
443             uri 
444             (Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () desc)
445         | Some t -> Printf.sprintf "<choice href=\"%s\" title=\"%s\">%s</choice>"
446             uri 
447             (Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () t)
448             (Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () desc)
449       in
450       let strchoices = 
451         String.concat "\n" 
452           (List.map (fun x -> tag_of_choice (choice_of_alias x)) choices)
453       in
454       prerr_endline (Printf.sprintf
455         "@@@ Ambiguous input at (%d,%d). Possible choices:\n\n%s\n\n@@@ End."
456           x y strchoices);
457       (*
458       let pre = Netconversion.ustring_sub `Enc_utf8  0 x text in
459       let err = Netconversion.ustring_sub `Enc_utf8  x (y-x) text in
460       let post = Netconversion.ustring_sub `Enc_utf8 y 
461          (Netconversion.ustring_length `Enc_utf8 text - y) text in
462       let title = "Disambiguation Error" in
463       (* let title = "" in *)
464       let marked = 
465         pre ^ "\005span class=\"error\" title=\"" ^ title ^ "\"\006" ^ err ^ "\005/span\006" ^ post in
466       let marked = Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false 
467       () (html_of_matita marked) in
468       *)
469       let strchoices = Printf.sprintf
470         "<ambiguity start=\"%d\" stop=\"%d\">%s</ambiguity>" x y strchoices
471       in raise (Ambiguous strchoices) 
472    (* | End_of_file -> ...          *)
473   in
474   MatitaAuthentication.set_status sid st;
475   parsed_len, 
476     Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false 
477       () (html_of_matita new_statements), new_unparsed, st
478
479 let register (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
480   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
481   let _env = cgi#environment in
482   
483   assert (cgi#arguments <> []);
484   let uid = cgi#argument_value "userid" in
485   let userpw = cgi#argument_value "password" in
486   (try 
487     MatitaAuthentication.add_user uid userpw;
488 (*    env#set_output_header_field "Location" "/index.html" *)
489     cgi#out_channel#output_string
490      ("<html><head><meta http-equiv=\"refresh\" content=\"2;url=/login.html\">"
491      ^ "</head><body>Redirecting to login page...</body></html>")
492    with
493    | MatitaAuthentication.UsernameCollision _ ->
494       cgi#set_header
495        ~cache:`No_cache 
496        ~content_type:"text/html; charset=\"utf-8\""
497        ();
498      cgi#out_channel#output_string
499       "<html><head></head><body>Error: User id collision!</body></html>"
500    | MatitaFilesystem.SvnError msg ->
501       cgi#set_header
502        ~cache:`No_cache 
503        ~content_type:"text/html; charset=\"utf-8\""
504        ();
505      cgi#out_channel#output_string
506       ("<html><head></head><body><p>Error: Svn checkout failed!<p><p><textarea>"
507        ^ msg ^ "</textarea></p></body></html>"));
508   cgi#out_channel#commit_work()
509 ;;
510
511 let login (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
512   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
513   let env = cgi#environment in
514   
515   assert (cgi#arguments <> []);
516   let uid = cgi#argument_value "userid" in
517   let userpw = cgi#argument_value "password" in
518   let pw,_ = MatitaAuthentication.lookup_user uid in
519
520   if pw = userpw then
521    begin
522    let ft = MatitaAuthentication.read_ft uid in
523    let _ = MatitaFilesystem.html_of_library uid ft in
524     let sid = MatitaAuthentication.create_session uid in
525     (* let cookie = Netcgi.Cookie.make "session" (Uuidm.to_string sid) in
526        cgi#set_header ~set_cookies:[cookie] (); *)
527     env#set_output_header_field 
528       "Set-Cookie" ("session=" ^ (Uuidm.to_string sid));
529 (*    env#set_output_header_field "Location" "/index.html" *)
530     cgi#out_channel#output_string
531      ("<html><head><meta http-equiv=\"refresh\" content=\"2;url=/index.html\">"
532      ^ "</head><body>Redirecting to Matita page...</body></html>")
533    end
534   else
535    begin
536     cgi#set_header
537       ~cache:`No_cache 
538       ~content_type:"text/html; charset=\"utf-8\""
539       ();
540     cgi#out_channel#output_string
541       "<html><head></head><body>Authentication error</body></html>"
542    end;
543     
544   cgi#out_channel#commit_work()
545   
546 ;;
547
548 let logout (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
549   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
550   let env = cgi#environment in
551   (try 
552     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
553     let sid = HExtlib.unopt sid in
554     MatitaAuthentication.logout_user sid;
555     cgi # set_header 
556       ~cache:`No_cache 
557       ~content_type:"text/html; charset=\"utf-8\""
558       ();
559     let text = read_file (rt_path () ^ "/logout.html") in
560     cgi#out_channel#output_string text
561   with
562   | Not_found _ -> 
563     cgi # set_header
564       ~status:`Internal_server_error
565       ~cache:`No_cache 
566       ~content_type:"text/html; charset=\"utf-8\""
567       ());
568   cgi#out_channel#commit_work()
569 ;;
570
571 exception File_already_exists;;
572
573 let save (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
574   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
575   let env = cgi#environment in
576   (try 
577     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
578     let sid = HExtlib.unopt sid in
579     let status = MatitaAuthentication.get_status sid in
580     let uid = MatitaAuthentication.user_of_session sid in
581     assert (cgi#arguments <> []);
582     let locked = cgi#argument_value "locked" in
583     let unlocked = cgi#argument_value "unlocked" in
584     let dir = cgi#argument_value "dir" in
585     let rel_filename = cgi # argument_value "file" in
586     let filename = libdir uid ^ "/" ^ rel_filename in
587     let force = bool_of_string (cgi#argument_value "force") in
588     let already_exists = Sys.file_exists filename in
589
590     if ((not force) && already_exists) then 
591       raise File_already_exists;
592
593     if dir = "true" then
594        Unix.mkdir filename 0o744
595     else 
596      begin
597       let oc = open_out filename in
598       output_string oc (locked ^ unlocked);
599       close_out oc;
600       if MatitaEngine.eos status unlocked then
601        begin
602         (* prerr_endline ("serializing proof objects..."); *)
603         GrafiteTypes.Serializer.serialize 
604           ~baseuri:(NUri.uri_of_string status#baseuri) status;
605         (* prerr_endline ("done."); *)
606        end;
607      end;
608     let old_flag =
609       try 
610         List.assoc rel_filename (MatitaAuthentication.read_ft uid)
611       with Not_found -> MatitaFilesystem.MUnversioned
612     in
613     (if old_flag <> MatitaFilesystem.MConflict &&
614        old_flag <> MatitaFilesystem.MAdd then
615       let newflag = 
616         if already_exists then MatitaFilesystem.MModified
617         else MatitaFilesystem.MAdd
618       in
619       MatitaAuthentication.set_file_flag uid [rel_filename, Some newflag]);
620     cgi # set_header 
621      ~cache:`No_cache 
622      ~content_type:"text/xml; charset=\"utf-8\""
623      ();
624     cgi#out_channel#output_string "<response>ok</response>"
625   with
626   | File_already_exists ->
627       cgi#out_channel#output_string "<response>cancelled</response>"
628   | Sys_error _ -> 
629     cgi # set_header
630       ~status:`Internal_server_error
631       ~cache:`No_cache 
632       ~content_type:"text/xml; charset=\"utf-8\""
633       ()
634   | e ->
635       let estr = Printexc.to_string e in
636       cgi#out_channel#output_string ("<response>" ^ estr ^ "</response>"));
637   cgi#out_channel#commit_work()
638 ;;
639
640 let initiate_commit (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
641   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
642   let _env = cgi#environment in
643   (try
644     let out = do_global_commit () in
645     cgi # set_header 
646       ~cache:`No_cache 
647       ~content_type:"text/xml; charset=\"utf-8\""
648       ();
649     cgi#out_channel#output_string "<commit>";
650     cgi#out_channel#output_string "<response>ok</response>";
651     cgi#out_channel#output_string ("<details>" ^ out ^ "</details>");
652     cgi#out_channel#output_string "</commit>"
653   with
654   | Not_found _ -> 
655     cgi # set_header
656       ~status:`Internal_server_error
657       ~cache:`No_cache 
658       ~content_type:"text/xml; charset=\"utf-8\""
659       ());
660   cgi#out_channel#commit_work()
661 ;;
662
663 let svn_update (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
664   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
665   let env = cgi#environment in
666   let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
667   let sid = HExtlib.unopt sid in
668   let uid = MatitaAuthentication.user_of_session sid in
669   (try
670     let files,anomalies,(added,conflict,del,upd,merged) = 
671       MatitaFilesystem.update_user uid 
672     in
673     let anomalies = String.concat "\n" anomalies in
674     let details = Printf.sprintf 
675       ("%d new files\n"^^
676        "%d deleted files\n"^^
677        "%d updated files\n"^^
678        "%d merged files\n"^^
679        "%d conflicting files\n\n" ^^
680        "Anomalies:\n%s") added del upd merged conflict anomalies
681     in
682     prerr_endline ("update details:\n" ^ details);
683     let details = 
684       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () details
685     in
686     MatitaAuthentication.set_file_flag uid files;
687     cgi # set_header 
688       ~cache:`No_cache 
689       ~content_type:"text/xml; charset=\"utf-8\""
690       ();
691     cgi#out_channel#output_string "<update>";
692     cgi#out_channel#output_string "<response>ok</response>";
693     cgi#out_channel#output_string ("<details>" ^ details ^ "</details>");
694     cgi#out_channel#output_string "</update>";
695   with
696   | Not_found _ -> 
697     cgi # set_header
698       ~status:`Internal_server_error
699       ~cache:`No_cache 
700       ~content_type:"text/xml; charset=\"utf-8\""
701       ());
702   cgi#out_channel#commit_work()
703 ;;
704
705 (* returns the length of the executed text and an html representation of the
706  * current metasenv*)
707 let advance (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
708   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
709   let env = cgi#environment in
710   (try 
711     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
712     let sid = HExtlib.unopt sid in
713     (*
714     cgi # set_header 
715       ~cache:`No_cache 
716       ~content_type:"text/xml; charset=\"utf-8\""
717       ();
718     *)
719     let text = cgi#argument_value "body" in
720     (* prerr_endline ("body =\n" ^ text); *)
721     let history = MatitaAuthentication.get_history sid in
722     let parsed_len, new_parsed, new_unparsed, new_status = advance0 sid text in
723     MatitaAuthentication.set_history sid (new_status::history);
724     let txt = output_status new_status in
725     let body = 
726        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\">" ^
727        new_parsed ^ "</parsed>" ^ txt 
728        ^ "</response>"
729     in 
730     (* prerr_endline ("sending advance response:\n" ^ body); *)
731     cgi # set_header 
732       ~cache:`No_cache 
733       ~content_type:"text/xml; charset=\"utf-8\""
734       ();
735     cgi#out_channel#output_string body
736    with
737   | Emphasized_error text ->
738 (* | MultiPassDisambiguator.DisambiguationError (offset,errorll) -> *)
739     let body = "<response><error>" ^ text ^ "</error></response>" in 
740     cgi # set_header 
741       ~cache:`No_cache 
742       ~content_type:"text/xml; charset=\"utf-8\""
743       ();
744     cgi#out_channel#output_string body
745   | Ambiguous text ->
746     let body = "<response>" ^ text ^ "</response>" in 
747     cgi # set_header 
748       ~cache:`No_cache 
749       ~content_type:"text/xml; charset=\"utf-8\""
750       ();
751     cgi#out_channel#output_string body
752   | Not_found _ -> 
753     cgi # set_header
754       ~status:`Internal_server_error
755       ~cache:`No_cache 
756       ~content_type:"text/xml; charset=\"utf-8\""
757       ());
758   cgi#out_channel#commit_work()
759 ;;
760
761 let gotoBottom (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
762   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
763   let env = cgi#environment in
764   (try 
765     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
766     let sid = HExtlib.unopt sid in
767     let history = MatitaAuthentication.get_history sid in
768
769     let rec aux parsed_len parsed_txt text =
770       try
771         prerr_endline ("evaluating: " ^ first_line text);
772         let plen,new_parsed,new_unparsed,_new_status = advance0 sid text in
773         aux (parsed_len+plen) (parsed_txt ^ new_parsed) new_unparsed
774       with 
775       | (* End_of_file *) _ -> 
776           let status = MatitaAuthentication.get_status sid in
777           GrafiteTypes.Serializer.serialize 
778             ~baseuri:(NUri.uri_of_string status#baseuri) status;
779           if parsed_len > 0 then 
780             MatitaAuthentication.set_history sid (status::history);
781           parsed_len, parsed_txt
782       (*| _ -> parsed_len, parsed_txt*)
783     in
784     (* 
785     cgi # set_header 
786       ~cache:`No_cache 
787       ~content_type:"text/xml; charset=\"utf-8\""
788       ();
789     *)
790     let text = cgi#argument_value "body" in
791     (* prerr_endline ("body =\n" ^ text); *)
792     let parsed_len, new_parsed = aux 0 "" text in
793     let status = MatitaAuthentication.get_status sid in
794     let txt = output_status status in
795     let body = 
796        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\">" ^
797        new_parsed ^ "</parsed>" ^ txt 
798        ^ "</response>"
799     in 
800     (*let body = 
801        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
802        ^ "</response>"
803     in*) 
804     (* prerr_endline ("sending goto bottom response:\n" ^ body); *)
805     cgi # set_header 
806       ~cache:`No_cache 
807       ~content_type:"text/xml; charset=\"utf-8\""
808       ();
809     cgi#out_channel#output_string body
810    with Not_found -> cgi#set_header ~status:`Internal_server_error 
811       ~cache:`No_cache 
812       ~content_type:"text/xml; charset=\"utf-8\"" ());
813   cgi#out_channel#commit_work() 
814 ;;
815
816 let gotoTop (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
817   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
818   let env = cgi#environment in
819   prerr_endline "executing goto Top";
820   (try 
821     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
822     let sid = HExtlib.unopt sid in
823     (*
824     cgi # set_header 
825       ~cache:`No_cache 
826       ~content_type:"text/xml; charset=\"utf-8\""
827       ();
828     *)
829     let status = MatitaAuthentication.get_status sid in
830     let uid = MatitaAuthentication.user_of_session sid in
831     let baseuri = status#baseuri in
832     let new_status = new MatitaEngine.status (Some uid) baseuri in
833     prerr_endline "gototop prima della time travel";
834     NCicLibrary.time_travel new_status;
835     prerr_endline "gototop dopo della time travel";
836     let new_history = [new_status] in 
837     MatitaAuthentication.set_history sid new_history;
838     MatitaAuthentication.set_status sid new_status;
839     NCicLibrary.time_travel new_status;
840     cgi # set_header 
841       ~cache:`No_cache 
842       ~content_type:"text/xml; charset=\"utf-8\""
843       ();
844     cgi#out_channel#output_string "<response>ok</response>"
845    with _ -> 
846      (cgi#set_header ~status:`Internal_server_error 
847       ~cache:`No_cache 
848       ~content_type:"text/xml; charset=\"utf-8\"" ();
849       cgi#out_channel#output_string "<response>ok</response>"));
850   cgi#out_channel#commit_work() 
851 ;;
852
853 let retract (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
854   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
855   let env = cgi#environment in
856   (try 
857     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
858     let sid = HExtlib.unopt sid in
859     (*
860     cgi # set_header 
861       ~cache:`No_cache 
862       ~content_type:"text/xml; charset=\"utf-8\""
863       ();
864     *)
865     let history = MatitaAuthentication.get_history sid in
866     let new_history,new_status =
867        match history with
868          _::(status::_ as history) ->
869           history, status
870       | [_] -> (prerr_endline "singleton";failwith "retract")
871       | _ -> (prerr_endline "nil"; assert false) in
872     prerr_endline ("prima della time travel");
873     NCicLibrary.time_travel new_status;
874     prerr_endline ("dopo della time travel");
875     MatitaAuthentication.set_history sid new_history;
876     MatitaAuthentication.set_status sid new_status;
877     prerr_endline ("baseuri after retract = " ^ new_status#baseuri);
878     let body = output_status new_status in
879     cgi # set_header 
880       ~cache:`No_cache 
881       ~content_type:"text/xml; charset=\"utf-8\""
882       ();
883     cgi#out_channel#output_string body
884    with _ -> cgi#set_header ~status:`Internal_server_error 
885       ~cache:`No_cache 
886       ~content_type:"text/xml; charset=\"utf-8\"" ());
887   cgi#out_channel#commit_work() 
888 ;;
889
890
891 let viewLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
892   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
893   let env = cgi#environment in
894   
895     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
896     let sid = HExtlib.unopt sid in
897     (*
898     cgi # set_header 
899       ~cache:`No_cache 
900       ~content_type:"text/html; charset=\"utf-8\""
901       ();
902     *)
903     let uid = MatitaAuthentication.user_of_session sid in
904     
905     let ft = MatitaAuthentication.read_ft uid in
906     let html = MatitaFilesystem.html_of_library uid ft in
907     cgi # set_header 
908       ~cache:`No_cache 
909       ~content_type:"text/html; charset=\"utf-8\""
910       ();
911     cgi#out_channel#output_string
912       ((*
913        "<html><head>\n" ^
914        "<title>XML Tree Control</title>\n" ^
915        "<link href=\"treeview/xmlTree.css\" type=\"text/css\" rel=\"stylesheet\">\n" ^
916        "<script src=\"treeview/xmlTree.js\" type=\"text/javascript\"></script>\n" ^
917        "<body>\n" ^ *)
918        html (* ^ "\n</body></html>" *) );
919     
920     let files,anomalies = MatitaFilesystem.stat_user uid in
921     let changed = HExtlib.filter_map 
922       (fun (n,f) -> if (f = Some MatitaFilesystem.MModified) then Some n else None) files
923     in
924     let changed = String.concat "\n" changed in
925     let anomalies = String.concat "\n" anomalies in
926     prerr_endline ("Changed:\n" ^ changed ^ "\n\nAnomalies:\n" ^ anomalies);
927   cgi#out_channel#commit_work()
928   
929 ;;
930
931 let resetLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
932   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
933   MatitaAuthentication.reset ();
934     cgi # set_header 
935       ~cache:`No_cache 
936       ~content_type:"text/html; charset=\"utf-8\""
937       ();
938     
939     cgi#out_channel#output_string
940       ("<html><head>\n" ^
941        "<title>Matitaweb Reset</title>\n" ^
942        "<body><H1>Reset completed</H1></body></html>");
943     cgi#out_channel#commit_work()
944
945 open Netcgi1_compat.Netcgi_types;;
946
947 (**********************************************************************)
948 (* Create the webserver                                               *)
949 (**********************************************************************)
950
951
952 let start() =
953   let (opt_list, cmdline_cfg) = Netplex_main.args() in
954
955   let use_mt = ref true in
956
957   let opt_list' =
958     [ "-mt", Arg.Set use_mt,
959       "  Use multi-threading instead of multi-processing"
960     ] @ opt_list in
961
962   Arg.parse 
963     opt_list'
964     (fun s -> raise (Arg.Bad ("Don't know what to do with: " ^ s)))
965     "usage: netplex [options]";
966   let parallelizer = 
967     if !use_mt then
968       Netplex_mt.mt()     (* multi-threading *)
969     else
970       Netplex_mp.mp() in  (* multi-processing *)
971 (*
972   let adder =
973     { Nethttpd_services.dyn_handler = (fun _ -> process1);
974       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
975       dyn_uri = None;                 (* not needed *)
976       dyn_translator = (fun _ -> ""); (* not needed *)
977       dyn_accept_all_conditionals = false;
978     } in
979 *)
980   let do_advance =
981     { Nethttpd_services.dyn_handler = (fun _ -> advance);
982       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
983       dyn_uri = None;                 (* not needed *)
984       dyn_translator = (fun _ -> ""); (* not needed *)
985       dyn_accept_all_conditionals = false;
986     } in
987   let do_retract =
988     { Nethttpd_services.dyn_handler = (fun _ -> retract);
989       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
990       dyn_uri = None;                 (* not needed *)
991       dyn_translator = (fun _ -> ""); (* not needed *)
992       dyn_accept_all_conditionals = false;
993     } in
994   let goto_bottom =
995     { Nethttpd_services.dyn_handler = (fun _ -> gotoBottom);
996       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
997       dyn_uri = None;                 (* not needed *)
998       dyn_translator = (fun _ -> ""); (* not needed *)
999       dyn_accept_all_conditionals = false;
1000     } in
1001   let goto_top =
1002     { Nethttpd_services.dyn_handler = (fun _ -> gotoTop);
1003       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1004       dyn_uri = None;                 (* not needed *)
1005       dyn_translator = (fun _ -> ""); (* not needed *)
1006       dyn_accept_all_conditionals = false;
1007     } in
1008   let retrieve =
1009     { Nethttpd_services.dyn_handler = (fun _ -> retrieve);
1010       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1011       dyn_uri = None;                 (* not needed *)
1012       dyn_translator = (fun _ -> ""); (* not needed *)
1013       dyn_accept_all_conditionals = false;
1014     } in
1015   let do_register =
1016     { Nethttpd_services.dyn_handler = (fun _ -> register);
1017       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1018       dyn_uri = None;                 (* not needed *)
1019       dyn_translator = (fun _ -> ""); (* not needed *)
1020       dyn_accept_all_conditionals = false;
1021     } in
1022   let do_login =
1023     { Nethttpd_services.dyn_handler = (fun _ -> login);
1024       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1025       dyn_uri = None;                 (* not needed *)
1026       dyn_translator = (fun _ -> ""); (* not needed *)
1027       dyn_accept_all_conditionals = false;
1028     } in
1029   let do_logout =
1030     { Nethttpd_services.dyn_handler = (fun _ -> logout);
1031       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1032       dyn_uri = None;                 (* not needed *)
1033       dyn_translator = (fun _ -> ""); (* not needed *)
1034       dyn_accept_all_conditionals = false;
1035     } in 
1036   let do_viewlib =
1037     { Nethttpd_services.dyn_handler = (fun _ -> viewLib);
1038       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1039       dyn_uri = None;                 (* not needed *)
1040       dyn_translator = (fun _ -> ""); (* not needed *)
1041       dyn_accept_all_conditionals = false;
1042     } in 
1043   let do_resetlib =
1044     { Nethttpd_services.dyn_handler = (fun _ -> resetLib);
1045       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1046       dyn_uri = None;                 (* not needed *)
1047       dyn_translator = (fun _ -> ""); (* not needed *)
1048       dyn_accept_all_conditionals = false;
1049     } in 
1050   let do_save =
1051     { Nethttpd_services.dyn_handler = (fun _ -> save);
1052       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1053       dyn_uri = None;                 (* not needed *)
1054       dyn_translator = (fun _ -> ""); (* not needed *)
1055       dyn_accept_all_conditionals = false;
1056     } in 
1057   let do_commit =
1058     { Nethttpd_services.dyn_handler = (fun _ -> initiate_commit);
1059       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1060       dyn_uri = None;                 (* not needed *)
1061       dyn_translator = (fun _ -> ""); (* not needed *)
1062       dyn_accept_all_conditionals = false;
1063     } in 
1064   let do_update =
1065     { Nethttpd_services.dyn_handler = (fun _ -> svn_update);
1066       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
1067       dyn_uri = None;                 (* not needed *)
1068       dyn_translator = (fun _ -> ""); (* not needed *)
1069       dyn_accept_all_conditionals = false;
1070     } in 
1071   
1072   
1073   let nethttpd_factory = 
1074     Nethttpd_plex.nethttpd_factory
1075       ~handlers:[ "advance", do_advance
1076                 ; "retract", do_retract
1077                 ; "bottom", goto_bottom
1078                 ; "top", goto_top
1079                 ; "open", retrieve 
1080                 ; "register", do_register
1081                 ; "login", do_login 
1082                 ; "logout", do_logout 
1083                 ; "reset", do_resetlib
1084                 ; "viewlib", do_viewlib
1085                 ; "save", do_save
1086                 ; "commit", do_commit
1087                 ; "update", do_update]
1088       () in
1089   MatitaInit.initialize_all ();
1090   MatitaAuthentication.deserialize ();
1091   Netplex_main.startup
1092     parallelizer
1093     Netplex_log.logger_factories   (* allow all built-in logging styles *)
1094     Netplex_workload.workload_manager_factories (* ... all ways of workload management *)
1095     [ nethttpd_factory ]           (* make this nethttpd available *)
1096     cmdline_cfg
1097 ;;
1098
1099 Sys.set_signal Sys.sigpipe Sys.Signal_ignore;
1100 start();;