]> matita.cs.unibo.it Git - helm.git/blob - helm/uwobo/uwobo.ml
- the mathql interpreter is not helm-dependent any more
[helm.git] / helm / uwobo / uwobo.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 Printf;;
30 open Uwobo_common;;
31
32  (* debugging settings *)
33 let debug = false ;;
34 let debug_level = `Notice ;;
35 let debug_print s = if debug then prerr_endline s ;;
36 Http_common.debug := false ;;
37
38   (* other settings *)
39 let daemon_name = "UWOBO OCaml" ;;
40 let default_log_base_file = "log/uwobo" ;; (* relative to execution dir *)
41 let log_extension = ".log" ;;
42 let default_port = 58080 ;;
43 let port_env_var = "UWOBO_PORT" ;;
44 let log_env_var = "UWOBO_LOG_FILE" ;; (* The extension _pid.log will be added *)
45 let default_media_type = "text/html" ;;
46 let default_encoding = "utf8" ;;
47 let port =
48   try
49     int_of_string (Sys.getenv port_env_var)
50   with
51   | Not_found -> default_port
52   | Failure "int_of_string" ->
53      prerr_endline "Warning: invalid port number" ;
54      exit (-1)
55 ;;
56 let logfilename_of_port port =
57  let basename =
58   try
59    Sys.getenv log_env_var
60   with
61    Not_found -> default_log_base_file
62  in
63   basename ^ "_" ^ string_of_int port ^ log_extension
64 ;;
65 let logfile = logfilename_of_port port;;
66 let logfile_perm = 0o640 ;;
67
68 let respond_html body outchan =
69   Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
70 ;;
71
72   (** perform an 'action' that can be applied to a list of keys or, if no keys
73   was given, to all keys *)
74 let act_on_keys
75   keys_param styles logger per_key_action all_keys_action all_keys logmsg
76 =
77   let keys =
78     try
79       Pcre.split ~pat:"," keys_param
80     with Http_types.Param_not_found _ -> []
81   in
82   match keys with
83   | [] -> (* no key provided, act on all stylesheets *)
84       logger#log (sprintf "%s all stylesheets (keys = %s) ..."
85         logmsg (String.concat ", " all_keys));
86       (try all_keys_action () with e -> logger#log (Printexc.to_string e));
87       logger#log (sprintf "Done! (all stylesheets)")
88   | keys ->
89       List.iter
90         (fun key -> (* act on a single stylesheet *)
91           logger#log (sprintf "%s stylesheet %s" logmsg key);
92           (try per_key_action key with e -> logger#log (Printexc.to_string e));
93           logger#log (sprintf "Done! (stylesheet %s)" key))
94         keys
95 ;;
96
97   (** parse parameters for '/apply' action *)
98 let parse_apply_params =
99   let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
100   let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
101   let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
102   List.fold_left
103     (fun (old_params, old_properties) (name, value) ->
104       match name with
105       | name when is_global_param name ->
106           let name = Pcre.replace ~pat:"^param\\." name in
107           ((fun x -> (old_params x) @ [name, value]), old_properties)
108       | name when is_local_param name ->
109           let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
110           let (key, name) = (pieces.(1), pieces.(2)) in
111           ((function
112             | x when x = key -> [name, value] @ (old_params x)
113             | x -> old_params x),
114            old_properties)
115       | name when is_property name ->
116           let name = Pcre.replace ~pat:"^prop\\." name in
117           (old_params, ((name, value) :: old_properties))
118       | _ -> (old_params, old_properties))
119     ((fun _ -> []), []) (* no parameters, no properties *)
120 ;;
121
122   (** Parse libxslt's message modes for error and debugging messages. Default is
123   to ignore mesages of both kind *)
124 let parse_libxslt_msgs_mode (req: Http_types.request) =
125   ((try
126     (match req#param "errormode" with
127     | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
128     | s when String.lowercase s = "comment" -> LibXsltMsgComment
129     | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
130     | err ->
131         raise (Uwobo_failure
132           (sprintf
133             "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
134             err "errormode" "ignore" "comment")))
135   with Http_types.Param_not_found _ -> LibXsltMsgIgnore),
136   (try
137     (match req#param "debugmode" with
138     | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
139     | s when String.lowercase s = "comment" -> LibXsltMsgComment
140     | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
141     | err ->
142         raise (Uwobo_failure
143           (sprintf
144             "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
145             err "debugmode" "ignore" "comment")))
146   with Http_types.Param_not_found _ -> LibXsltMsgIgnore))
147 ;;
148
149   (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
150   on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
151   received from ~res_pipe *)
152 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
153 (*   debug_print (sprintf "Sending command '%s' to grandparent ..." cmd); *)
154   output_string cmd_pipe (cmd ^ "\n");  (* send command to grandfather *)
155   flush cmd_pipe;
156   let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
157   let (read_fds, _, _) =  (* wait for an answer *)
158     Unix.select [res_pipe_fd] [] [] 60.0
159   in
160   (match read_fds with
161   | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
162       Http_daemon.send_basic_headers ~code:200 outchan;
163       Http_daemon.send_header "Content-Type" "text/html" outchan;
164       Http_daemon.send_CRLF outchan;
165       (try
166         while true do
167           output_string outchan ((input_line res_pipe) ^ "\n")
168         done
169       with End_of_file -> flush outchan)
170   | _ ->  (* no answer received from grandfather *)
171       return_error "Timeout!" outchan)
172 ;;
173
174 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE, kill_cmd_RE) =
175   (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ",
176    Pcre.regexp "^kill")
177 ;;
178
179   (** raised by child processes when HTTP daemon process have to be restarted *)
180 exception Restart_HTTP_daemon ;;
181
182   (** log a list of libxslt's messages using a processing logger *)
183 let log_libxslt_msgs logger libxslt_logger =
184   List.iter
185     (function
186       | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
187       | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
188     libxslt_logger#msgs
189 ;;
190
191   (* LibXSLT logger *)
192 let veillogger = new Uwobo_common.libXsltLogger ;;
193
194   (* start_new_session cmd_pipe_exit res_pipe_entrance outchan port logfile
195   @param cmd_pipe Pipe to be closed before forking
196   @param res_pipe Pipe to be closed before forking
197   @param outchan  To be closed before forking
198   @param port The port to be used
199   @param logfile The logfile to redirect the stdout and sterr to
200   *)
201   (* It can raise Failure "Connection refused" *)
202   (* It can raise Failure "Port already in use" *)
203 let start_new_session cmd_pipe res_pipe outchan port logfile =
204  let environment =
205   (* Here I am loosing the current value of port_env_var; *)
206   (* this should not matter                               *)
207   Unix.putenv port_env_var (string_of_int port) ;
208   Unix.environment ()
209  in
210   (* Let's check that the port is free *)
211   (try
212     ignore
213      (Http_client.Convenience.http_head_message
214        ("http://127.0.0.1:" ^ string_of_int port ^ "/help")) ;
215     raise (Failure "Port already in use")
216    with
217     Failure "Connection refused" -> ()
218   ) ;
219   match Unix.fork () with
220      0 ->
221        Unix.handle_unix_error
222         (function () ->
223           (* 1. We close all the open pipes to avoid duplicating them *)
224           Unix.close (Unix.descr_of_out_channel cmd_pipe) ;
225           Unix.close (Unix.descr_of_in_channel res_pipe) ;
226           Unix.close (Unix.descr_of_out_channel outchan) ;
227           (* 2. We redirect stdout and stderr to the logfile *)
228           Unix.close Unix.stdout ;
229           assert
230            (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
231              0o664 = Unix.stdout) ;
232           Unix.close Unix.stderr ;
233           assert
234            (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
235              0o664 = Unix.stderr) ;
236           prerr_endline "***** Starting a new session" ;
237           (* 3. We exec a new copy of uwobo *)
238           Unix.execve Sys.executable_name [||] environment ; 
239           (* It should never reach this point *)
240           assert false
241         ) ()
242    | child when child > 0 ->
243       (* let's check if the new UWOBO started correctly *)
244       Unix.sleep 5 ;
245       (* It can raise Failure "Connection refused" *)
246       ignore
247         (Http_client.Convenience.http_head_message
248           ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
249    | _ -> failwith "Can't fork :-("
250 ;;
251
252   (* request handler action
253   @param syslogger Uwobo_logger.sysLogger instance used for logginf
254   @param styles Uwobo_styles.styles instance which keeps the stylesheets list
255   @param cmd_pipe output _channel_ used to _write_ update messages
256   @param res_pipe input _channel_ used to _read_ grandparent results
257   @param req http request instance
258   @param outchan output channel connected to http client
259   *)
260 let callback
261   ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
262   =
263   try
264     syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
265     syslogger#log `Debug (sprintf "Received request: %s" req#path);
266     (match req#path with
267     | "/add" ->
268         (let bindings = req#paramAll "bind" in
269         if bindings = [] then
270           return_error "No [key,stylesheet] binding provided" outchan
271         else begin
272           let cmd = sprintf "add %s" (String.concat ";" bindings) in
273           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
274         end)
275     | "/kill" ->
276         let logger = new Uwobo_logger.processingLogger () in
277          logger#log "Exiting" ;
278          respond_html logger#asHtml outchan ;
279          let cmd = "kill" in
280           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
281     | "/newsession" ->
282         let logger = new Uwobo_logger.processingLogger () in
283         let port = int_of_string (req#param "port") in
284         let logfile = logfilename_of_port port in
285         (try
286           start_new_session cmd_pipe res_pipe outchan port logfile ;
287           logger#log (sprintf "New session started: port = %d" port) ;
288           respond_html logger#asHtml outchan
289          with
290             Failure "int_of_string" ->
291              logger#log (sprintf "Invalid port number") ;
292              respond_html logger#asHtml outchan
293           | Failure "Port already in use" ->
294              Uwobo_common.return_error "port already in use" outchan
295           | Failure "Connection refused" ->
296              let log = ref [] in
297               (try
298                 let ch = open_in logfile in
299                  while true do log := (input_line ch ^ "\n") :: !log ; done
300                with
301                   Sys_error _
302                 | End_of_file -> ()
303               ) ;
304               let rec get_last_lines acc =
305                function
306                   (n,he::tl) when n > 0 ->
307                     get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
308                 | _ -> acc
309               in
310                (* we just show the last 10 lines of the log file *)
311                let msg =
312                 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
313                  get_last_lines "" (10,!log)
314                in
315                 Uwobo_common.return_error "daemon not initialized"
316                  ~body:msg outchan)
317     | "/remove" ->
318           let cmd = sprintf "remove %s" (req#param "keys") in
319           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
320     | "/reload" ->
321           let cmd = sprintf "reload %s" (req#param "keys") in
322           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
323     | "/list" ->
324         (let logger = new Uwobo_logger.processingLogger () in
325         (match styles#list with
326         | [] -> logger#log "No stylesheets loaded (yet)!"
327         | l ->
328             logger#log "Stylesheets list:";
329             List.iter (fun s -> logger#log s) l);
330         respond_html logger#asHtml outchan)
331     | "/apply" ->
332         let logger = new Uwobo_logger.processingLogger () in
333         veillogger#clearMsgs;
334         let xmluri = req#param "xmluri" in
335         let keys = Pcre.split ~pat:"," (req#param "keys") in
336         (* notation: "local" parameters are those defined on a per-stylesheet
337         pasis (i.e. param.key.param=value), "global" parameters are those
338         defined for all stylesheets (i.e. param.param=value) *)
339         let (params, props) = parse_apply_params req#params in
340         let (libxslt_errormode, libxslt_debugmode) =
341           parse_libxslt_msgs_mode req
342         in
343         syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
344         let domImpl = Gdome.domImplementation () in
345         let input = domImpl#createDocumentFromURI ~uri:xmluri () in
346         syslogger#log `Debug "Applying stylesheet chain ...";
347         (try
348           let (write_result, media_type, encoding) = (* out_channel -> unit *)
349             Uwobo_engine.apply
350               ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
351               ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
352               input
353           in
354           let content_type = (* value of Content-Type HTTP response header *)
355             sprintf "%s; charset=%s"
356               (match media_type with None -> default_media_type | Some t -> t)
357               (match encoding with None -> default_encoding | Some e -> e)
358           in
359           syslogger#log `Debug
360             (sprintf "sending output to client (Content-Type: %s)...."
361               content_type);
362           Http_daemon.send_basic_headers ~code:200 outchan;
363           Http_daemon.send_header "Content-Type" content_type outchan;
364           Http_daemon.send_CRLF outchan;
365           write_result outchan
366         with Uwobo_failure errmsg ->
367           return_error
368             ("Stylesheet chain application failed: " ^ errmsg)
369             ~body: ("<h2>LibXSLT's messages:</h2>" ^
370               String.concat "<br />\n"
371                 (List.map string_of_xslt_msg veillogger#msgs))
372             outchan)
373     | "/help" -> respond_html usage_string outchan
374     | invalid_request ->
375         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
376     syslogger#log `Debug (sprintf "%s done!" req#path);
377   with
378   | Http_types.Param_not_found attr_name ->
379       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
380   | exc ->
381       return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
382 ;;
383
384   (* UWOBO's startup *)
385 let main () =
386     (* (1) system logger *)
387   let logger_outchan =
388    debug_print (sprintf "Logging to file %s" logfile);
389    open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
390   in
391   let syslogger =
392     new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
393   in
394   syslogger#enable;
395     (* (2) stylesheets list *)
396   let styles = new Uwobo_styles.styles in
397     (* (3) clean up actions *)
398   let last_process = ref true in
399   let http_child = ref None in
400   let die_nice () = (** at_exit callback *)
401     if !last_process then begin
402       (match !http_child with
403       | None -> ()
404       | Some pid -> Unix.kill pid Sys.sigterm);
405       syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
406       syslogger#disable;
407       close_out logger_outchan
408     end
409   in
410   at_exit die_nice;
411   ignore (Sys.signal Sys.sigterm
412     (Sys.Signal_handle (fun _ -> raise Sys.Break)));
413   syslogger#log `Notice
414     (sprintf "%s started and listening on port %d" daemon_name port);
415   syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
416   Unix.putenv "http_proxy" "";  (* reset http_proxy to avoid libxslt problems *)
417   while true do
418     let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
419     let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
420     match Unix.fork () with
421     | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
422         http_child := Some child;
423         let stop_http_daemon () =  (* kill child *)
424           debug_print (sprintf "UWOBOmaster: killing pid %d" child);
425           Unix.kill child Sys.sigterm;  (* kill child ... *)
426           ignore (Unix.waitpid [] child);  (* ... and its zombie *)
427         in
428         Unix.close cmd_pipe_entrance;
429         Unix.close res_pipe_exit;
430         let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
431         let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
432         (try
433           while true do
434             (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
435             child process has been killed *)
436             debug_print "UWOBOmaster: waiting for commands ...";
437             let cmd = input_line cmd_pipe in
438             debug_print (sprintf "UWOBOmaster: received %s command" cmd);
439             (match cmd with  (* command from grandchild *)
440             | "test" ->
441                 stop_http_daemon ();
442                 output_string res_pipe "UWOBOmaster: Hello, world!\n";
443                 flush res_pipe;
444                 raise Restart_HTTP_daemon
445             | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
446                 exit 0
447             | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
448                 let bindings =
449                   Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
450                 in
451                 stop_http_daemon ();
452                 let logger = new Uwobo_logger.processingLogger () in
453                 List.iter
454                   (fun binding -> (* add a <key, stylesheet> binding *)
455                     let pieces = Pcre.split ~pat:"," binding in
456                     match pieces with
457                     | [key; style] ->
458                         logger#log (sprintf "adding binding <%s,%s>" key style);
459                         veillogger#clearMsgs;
460                         (try
461                           veillogger#clearMsgs;
462                           styles#add key style;
463                           log_libxslt_msgs logger veillogger;
464                         with e ->
465                           logger#log (Printexc.to_string e))
466                     | _ -> logger#log (sprintf "invalid binding %s" binding))
467                   bindings;
468                 output_string res_pipe logger#asHtml;
469                 flush res_pipe;
470                 raise Restart_HTTP_daemon
471             | line when Pcre.pmatch ~rex:remove_cmd_RE line ->  (* /remove *)
472                 stop_http_daemon ();
473                 let arg = Pcre.replace ~rex:remove_cmd_RE line in
474                 let logger = new Uwobo_logger.processingLogger () in
475                 veillogger#clearMsgs;
476                 act_on_keys
477                   arg styles logger
478                   styles#remove (fun () -> styles#removeAll) styles#keys
479                   "removing";
480                 log_libxslt_msgs logger veillogger;
481                 output_string res_pipe (logger#asHtml);
482                 raise Restart_HTTP_daemon
483             | line when Pcre.pmatch ~rex:reload_cmd_RE line ->  (* /reload *)
484                 stop_http_daemon ();
485                 let arg = Pcre.replace ~rex:reload_cmd_RE line in
486                 let logger = new Uwobo_logger.processingLogger () in
487                 veillogger#clearMsgs;
488                 act_on_keys
489                   arg styles logger
490                   styles#reload (fun () -> styles#reloadAll) styles#keys
491                   "reloading";
492                 output_string res_pipe (logger#asHtml);
493                 raise Restart_HTTP_daemon
494             | cmd ->  (* invalid interprocess command received *)
495                 syslogger#log `Warning
496                   (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
497           done
498         with Restart_HTTP_daemon ->
499           close_in cmd_pipe;  (* these calls close also fds *)
500           close_out res_pipe;)
501     | 0 ->  (* (5) child: serve http requests *)
502         Unix.close cmd_pipe_exit;
503         Unix.close res_pipe_entrance;
504         last_process := false;
505         let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
506         let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
507         debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
508           (* next invocation doesn't return, process will keep on serving HTTP
509           requests until it will get killed by father *)
510         Http_daemon.start'~port ~mode:`Fork
511           (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
512     | _ (* < 0 *) ->  (* fork failed :-((( *)
513         failwith "Can't fork :-("
514   done
515 ;;
516
517   (* daemon initialization *)
518 try
519   Sys.catch_break true;
520   main ()
521 with Sys.Break -> ()  (* 'die_nice' registered with at_exit *)
522 ;;
523