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