3 * Stefano Zacchiroli <zack@cs.unibo.it>
4 * for the HELM Team http://helm.cs.unibo.it/
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.
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.
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.
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,
25 * For details, see the HELM World-Wide-Web page,
26 * http://helm.cs.unibo.it/
32 (* debugging settings *)
34 let debug_level = `Notice ;;
35 let debug_print s = if debug then prerr_endline s ;;
36 Http_common.debug := false ;;
39 (* First of all we load the configuration *)
41 let configuration_file = "/projects/helm/etc/uwobo.conf.xml" in
42 Helm_registry.load_from configuration_file
46 let daemon_name = "UWOBO OCaml" ;;
47 let default_media_type = "text/html" ;;
48 let default_encoding = "utf8" ;;
50 let get_media_type props =
52 List.assoc "media-type" props
54 Not_found -> default_media_type
57 let get_encoding props =
59 List.assoc "encoding" props
61 Not_found -> default_encoding
64 let port = Helm_registry.get_int "uwobo.port";;
66 let logfilename_of_port port =
67 let basename = Helm_registry.get "uwobo.log_basename" in
68 let extension = Helm_registry.get "uwobo.log_extension" in
69 basename ^ "_" ^ string_of_int port ^ extension
72 let logfile = logfilename_of_port port;;
73 let logfile_perm = 0o640 ;;
75 let respond_html body outchan =
76 Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
79 (** perform an 'action' that can be applied to a list of keys or, if no keys
80 was given, to all keys *)
82 keys_param styles logger per_key_action all_keys_action all_keys logmsg
86 Pcre.split ~pat:"," keys_param
87 with Http_types.Param_not_found _ -> []
90 | [] -> (* no key provided, act on all stylesheets *)
91 logger#log (sprintf "%s all stylesheets (keys = %s) ..."
92 logmsg (String.concat ", " all_keys));
93 (try all_keys_action () with e -> logger#log (Printexc.to_string e));
94 logger#log (sprintf "Done! (all stylesheets)")
97 (fun key -> (* act on a single stylesheet *)
98 logger#log (sprintf "%s stylesheet %s" logmsg key);
99 (try per_key_action key with e -> logger#log (Printexc.to_string e));
100 logger#log (sprintf "Done! (stylesheet %s)" key))
104 (** parse parameters for '/apply' action *)
105 let parse_apply_params =
106 let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
107 let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
108 let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
110 (fun (old_params, old_properties) (name, value) ->
112 | name when is_global_param name ->
113 let name = Pcre.replace ~pat:"^param\\." name in
114 ((fun x -> (old_params x) @ [name, value]), old_properties)
115 | name when is_local_param name ->
116 let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
117 let (key, name) = (pieces.(1), pieces.(2)) in
119 | x when x = key -> [name, value] @ (old_params x)
120 | x -> old_params x),
122 | name when is_property name ->
123 let name = Pcre.replace ~pat:"^prop\\." name in
124 (old_params, ((name, value) :: old_properties))
125 | _ -> (old_params, old_properties))
126 ((fun _ -> []), []) (* no parameters, no properties *)
129 (** Parse libxslt's message modes for error and debugging messages. Default is
130 to ignore mesages of both kind *)
131 let parse_libxslt_msgs_mode (req: Http_types.request) =
133 (match req#param "errormode" with
134 | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
135 | s when String.lowercase s = "comment" -> LibXsltMsgComment
136 | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
140 "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
141 err "errormode" "ignore" "comment")))
142 with Http_types.Param_not_found _ -> LibXsltMsgIgnore),
144 (match req#param "debugmode" with
145 | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
146 | s when String.lowercase s = "comment" -> LibXsltMsgComment
147 | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
151 "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
152 err "debugmode" "ignore" "comment")))
153 with Http_types.Param_not_found _ -> LibXsltMsgIgnore))
156 (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
157 on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
158 received from ~res_pipe *)
159 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
160 (* debug_print (sprintf "Sending command '%s' to grandparent ..." cmd); *)
161 output_string cmd_pipe (cmd ^ "\n"); (* send command to grandfather *)
163 let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
164 let (read_fds, _, _) = (* wait for an answer *)
165 Unix.select [res_pipe_fd] [] [] 60.0
168 | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
169 Http_daemon.send_basic_headers ~code:200 outchan;
170 Http_daemon.send_header "Content-Type" "text/html" outchan;
171 Http_daemon.send_CRLF outchan;
174 output_string outchan ((input_line res_pipe) ^ "\n")
176 with End_of_file -> flush outchan)
177 | _ -> (* no answer received from grandfather *)
178 return_error "Timeout!" outchan)
181 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE, kill_cmd_RE) =
182 (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ",
186 (** raised by child processes when HTTP daemon process have to be restarted *)
187 exception Restart_HTTP_daemon ;;
189 (** log a list of libxslt's messages using a processing logger *)
190 let log_libxslt_msgs logger libxslt_logger =
193 | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
194 | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
199 let veillogger = new Uwobo_common.libXsltLogger ;;
201 (* start_new_session cmd_pipe_exit res_pipe_entrance outchan port logfile
202 @param cmd_pipe Pipe to be closed before forking
203 @param res_pipe Pipe to be closed before forking
204 @param outchan To be closed before forking
205 @param port The port to be used
206 @param logfile The logfile to redirect the stdout and sterr to
208 (* It can raise Failure "Connection refused" *)
209 (* It can raise Failure "Port already in use" *)
210 let start_new_session cmd_pipe res_pipe outchan port logfile =
211 (* Let's check that the port is free *)
214 (Http_client.http_get
215 ("http://127.0.0.1:" ^ string_of_int port ^ "/help")) ;
216 raise (Failure "Port already in use")
218 Unix.Unix_error (Unix.ECONNREFUSED, _, _) -> ()
220 match Unix.fork () with
222 Unix.handle_unix_error
224 (* 1. We close all the open pipes to avoid duplicating them *)
225 Unix.close (Unix.descr_of_out_channel cmd_pipe) ;
226 Unix.close (Unix.descr_of_in_channel res_pipe) ;
227 Unix.close (Unix.descr_of_out_channel outchan) ;
228 (* 2. We redirect stdout and stderr to the logfile *)
229 Unix.close Unix.stdout ;
231 (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
232 0o664 = Unix.stdout) ;
233 Unix.close Unix.stderr ;
235 (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
236 0o664 = Unix.stderr) ;
237 prerr_endline "***** Starting a new session" ;
239 (* 3. We set up a new environment *)
241 (* Here I am loosing the current value of port_env_var; *)
242 (* this should not matter *)
243 Unix.putenv "UWOBO__PORT" (string_of_int port) ;
246 (* 4. We exec a new copy of uwobo *)
247 Unix.execve Sys.executable_name [||] environment ;
248 (* It should never reach this point *)
251 | child when child > 0 ->
252 (* let's check if the new UWOBO started correctly *)
254 (* It can raise Failure "Connection refused" *)
257 (Http_client.http_get
258 ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
259 with Unix.Unix_error (Unix.ECONNREFUSED, _, _) ->
260 raise (Failure "Connection refused"))
261 | _ -> failwith "Can't fork :-("
264 (* request handler action
265 @param syslogger Uwobo_logger.sysLogger instance used for logginf
266 @param styles Uwobo_styles.styles instance which keeps the stylesheets list
267 @param cmd_pipe output _channel_ used to _write_ update messages
268 @param res_pipe input _channel_ used to _read_ grandparent results
269 @param req http request instance
270 @param outchan output channel connected to http client
273 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
276 syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
277 syslogger#log `Debug (sprintf "Received request: %s" req#path);
280 (let bindings = req#paramAll "bind" in
281 if bindings = [] then
282 return_error "No [key,stylesheet] binding provided" outchan
284 let cmd = sprintf "add %s" (String.concat ";" bindings) in
285 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
288 let logger = new Uwobo_logger.processingLogger () in
289 logger#log "Exiting" ;
290 respond_html logger#asHtml outchan ;
292 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
294 let logger = new Uwobo_logger.processingLogger () in
295 let port = int_of_string (req#param "port") in
296 let logfile = logfilename_of_port port in
298 start_new_session cmd_pipe res_pipe outchan port logfile ;
299 logger#log (sprintf "New session started: port = %d" port) ;
300 respond_html logger#asHtml outchan
302 Failure "int_of_string" ->
303 logger#log (sprintf "Invalid port number") ;
304 respond_html logger#asHtml outchan
305 | Failure "Port already in use" ->
306 Uwobo_common.return_error "port already in use" outchan
307 | Failure "Connection refused" ->
310 let ch = open_in logfile in
311 while true do log := (input_line ch ^ "\n") :: !log ; done
316 let rec get_last_lines acc =
318 (n,he::tl) when n > 0 ->
319 get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
322 (* we just show the last 10 lines of the log file *)
324 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
325 get_last_lines "" (10,!log)
327 Uwobo_common.return_error "daemon not initialized"
330 let cmd = sprintf "remove %s" (req#param "keys") in
331 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
333 let cmd = sprintf "reload %s" (req#param "keys") in
334 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
336 (let logger = new Uwobo_logger.processingLogger () in
337 (match styles#list with
338 | [] -> logger#log "No stylesheets loaded (yet)!"
340 logger#log "Stylesheets list:";
341 List.iter (fun s -> logger#log s) l);
342 respond_html logger#asHtml outchan)
344 let logger = new Uwobo_logger.processingLogger () in
345 veillogger#clearMsgs;
346 let xmluri = req#param "xmluri" in
347 let keys = Pcre.split ~pat:"," (req#param "keys") in
348 (* notation: "local" parameters are those defined on a per-stylesheet
349 pasis (i.e. param.key.param=value), "global" parameters are those
350 defined for all stylesheets (i.e. param.param=value) *)
351 let (params, props) = parse_apply_params req#params in
352 let (libxslt_errormode, libxslt_debugmode) =
353 parse_libxslt_msgs_mode req
355 syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
356 let domImpl = Gdome.domImplementation () in
357 let input = domImpl#createDocumentFromURI ~uri:xmluri () in
358 syslogger#log `Debug "Applying stylesheet chain ...";
360 let (write_result, media_type, encoding) = (* out_channel -> unit *)
362 ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
363 ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
366 let content_type = (* value of Content-Type HTTP response header *)
367 sprintf "%s; charset=%s"
368 (match media_type with None -> get_media_type props | Some t -> t)
369 (match encoding with None -> get_encoding props | Some e -> e)
372 (sprintf "sending output to client (Content-Type: %s)...."
374 Http_daemon.send_basic_headers ~code:200 outchan;
375 Http_daemon.send_header "Content-Type" content_type outchan;
376 Http_daemon.send_CRLF outchan;
378 with Uwobo_failure errmsg ->
380 ("Stylesheet chain application failed: " ^ errmsg)
381 ~body: ("<h2>LibXSLT's messages:</h2>" ^
382 String.concat "<br />\n"
383 (List.map string_of_xslt_msg veillogger#msgs))
385 | "/help" -> respond_html usage_string outchan
387 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
388 syslogger#log `Debug (sprintf "%s done!" req#path);
390 | Http_types.Param_not_found attr_name ->
391 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
393 return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
396 (* UWOBO's startup *)
398 (* (1) system logger *)
400 debug_print (sprintf "Logging to file %s" logfile);
401 open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
404 new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
407 (* (2) stylesheets list *)
408 let styles = new Uwobo_styles.styles in
409 (* (3) clean up actions *)
410 let last_process = ref true in
411 let http_child = ref None in
412 let die_nice () = (** at_exit callback *)
413 if !last_process then begin
414 (match !http_child with
416 | Some pid -> Unix.kill pid Sys.sigterm);
417 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
419 close_out logger_outchan
423 ignore (Sys.signal Sys.sigterm
424 (Sys.Signal_handle (fun _ -> raise Sys.Break)));
425 syslogger#log `Notice
426 (sprintf "%s started and listening on port %d" daemon_name port);
427 syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
428 Unix.putenv "http_proxy" ""; (* reset http_proxy to avoid libxslt problems *)
430 let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
431 let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
432 match Unix.fork () with
433 | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
434 http_child := Some child;
435 let stop_http_daemon () = (* kill child *)
436 debug_print (sprintf "UWOBOmaster: killing pid %d" child);
437 Unix.kill child Sys.sigterm; (* kill child ... *)
438 ignore (Unix.waitpid [] child); (* ... and its zombie *)
440 Unix.close cmd_pipe_entrance;
441 Unix.close res_pipe_exit;
442 let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
443 let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
446 (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
447 child process has been killed *)
448 debug_print "UWOBOmaster: waiting for commands ...";
449 let cmd = input_line cmd_pipe in
450 debug_print (sprintf "UWOBOmaster: received %s command" cmd);
451 (match cmd with (* command from grandchild *)
454 output_string res_pipe "UWOBOmaster: Hello, world!\n";
456 raise Restart_HTTP_daemon
457 | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
459 | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
461 Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
464 let logger = new Uwobo_logger.processingLogger () in
466 (fun binding -> (* add a <key, stylesheet> binding *)
467 let pieces = Pcre.split ~pat:"," binding in
470 logger#log (sprintf "adding binding <%s,%s>" key style);
471 veillogger#clearMsgs;
473 veillogger#clearMsgs;
474 styles#add key style;
475 log_libxslt_msgs logger veillogger;
477 logger#log (Printexc.to_string e))
478 | _ -> logger#log (sprintf "invalid binding %s" binding))
480 output_string res_pipe logger#asHtml;
482 raise Restart_HTTP_daemon
483 | line when Pcre.pmatch ~rex:remove_cmd_RE line -> (* /remove *)
485 let arg = Pcre.replace ~rex:remove_cmd_RE line in
486 let logger = new Uwobo_logger.processingLogger () in
487 veillogger#clearMsgs;
490 styles#remove (fun () -> styles#removeAll) styles#keys
492 log_libxslt_msgs logger veillogger;
493 output_string res_pipe (logger#asHtml);
494 raise Restart_HTTP_daemon
495 | line when Pcre.pmatch ~rex:reload_cmd_RE line -> (* /reload *)
497 let arg = Pcre.replace ~rex:reload_cmd_RE line in
498 let logger = new Uwobo_logger.processingLogger () in
499 veillogger#clearMsgs;
502 styles#reload (fun () -> styles#reloadAll) styles#keys
504 output_string res_pipe (logger#asHtml);
505 raise Restart_HTTP_daemon
506 | cmd -> (* invalid interprocess command received *)
507 syslogger#log `Warning
508 (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
510 with Restart_HTTP_daemon ->
511 close_in cmd_pipe; (* these calls close also fds *)
513 | 0 -> (* (5) child: serve http requests *)
514 Unix.close cmd_pipe_exit;
515 Unix.close res_pipe_entrance;
516 last_process := false;
517 let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
518 let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
519 debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
520 (* next invocation doesn't return, process will keep on serving HTTP
521 requests until it will get killed by father *)
522 Http_daemon.start'~port ~mode:`Fork
523 (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
524 | _ (* < 0 *) -> (* fork failed :-((( *)
525 failwith "Can't fork :-("
529 (* daemon initialization *)
531 Sys.catch_break true;
533 with Sys.Break -> () (* 'die_nice' registered with at_exit *)