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 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" ;;
49 int_of_string (Sys.getenv port_env_var)
51 | Not_found -> default_port
52 | Failure "int_of_string" ->
53 prerr_endline "Warning: invalid port number" ;
56 let logfilename_of_port ~use_log_env_var port =
58 if use_log_env_var then Sys.getenv log_env_var else raise Not_found
61 default_log_base_file ^ (string_of_int port) ^ default_log_extension)
63 let logfile = logfilename_of_port true port;;
64 let logfile_perm = 0o640 ;;
66 let respond_html body outchan =
67 Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
70 (** perform an 'action' that can be applied to a list of keys or, if no keys
71 was given, to all keys *)
73 keys_param styles logger per_key_action all_keys_action all_keys logmsg
77 Pcre.split ~pat:"," keys_param
78 with Http_types.Param_not_found _ -> []
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)")
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))
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
101 (fun (old_params, old_properties) (name, value) ->
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
110 | x when x = key -> [name, value] @ (old_params x)
111 | x -> old_params x),
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 *)
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) =
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
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),
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
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))
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 *)
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
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;
165 output_string outchan ((input_line res_pipe) ^ "\n")
167 with End_of_file -> flush outchan)
168 | _ -> (* no answer received from grandfather *)
169 return_error "Timeout!" outchan)
172 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE, kill_cmd_RE) =
173 (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ",
177 (** raised by child processes when HTTP daemon process have to be restarted *)
178 exception Restart_HTTP_daemon ;;
180 (** log a list of libxslt's messages using a processing logger *)
181 let log_libxslt_msgs logger libxslt_logger =
184 | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
185 | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
190 let veillogger = new Uwobo_common.libXsltLogger ;;
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
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 =
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) ;
208 (* Let's check that the port is free *)
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")
215 Failure "Connection refused" -> ()
217 match Unix.fork () with
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 ;
226 (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
227 0o664 = Unix.stdout) ;
228 Unix.close Unix.stderr ;
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 *)
237 | child when child > 0 ->
238 (* let's check if the new UWOBO started correctly *)
240 (* It can raise Failure "Connection refused" *)
242 (Http_client.Convenience.http_head_message
243 ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
244 | _ -> failwith "Can't fork :-("
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
256 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
259 syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
260 syslogger#log `Debug (sprintf "Received request: %s" req#path);
263 (let bindings = req#paramAll "bind" in
264 if bindings = [] then
265 return_error "No [key,stylesheet] binding provided" outchan
267 let cmd = sprintf "add %s" (String.concat ";" bindings) in
268 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
271 let logger = new Uwobo_logger.processingLogger () in
272 logger#log "Exiting" ;
273 respond_html logger#asHtml outchan ;
275 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
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
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
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" ->
293 let ch = open_in logfile in
294 while true do log := (input_line ch ^ "\n") :: !log ; done
299 let rec get_last_lines acc =
301 (n,he::tl) when n > 0 ->
302 get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
305 (* we just show the last 10 lines of the log file *)
307 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
308 get_last_lines "" (10,!log)
310 Uwobo_common.return_error "daemon not initialized"
313 let cmd = sprintf "remove %s" (req#param "keys") in
314 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
316 let cmd = sprintf "reload %s" (req#param "keys") in
317 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
319 (let logger = new Uwobo_logger.processingLogger () in
320 (match styles#list with
321 | [] -> logger#log "No stylesheets loaded (yet)!"
323 logger#log "Stylesheets list:";
324 List.iter (fun s -> logger#log s) l);
325 respond_html logger#asHtml outchan)
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
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 ...";
343 let (write_result, media_type, encoding) = (* out_channel -> unit *)
345 ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
346 ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
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)
355 (sprintf "sending output to client (Content-Type: %s)...."
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;
361 with Uwobo_failure errmsg ->
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))
368 | "/help" -> respond_html usage_string outchan
370 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
371 syslogger#log `Debug (sprintf "%s done!" req#path);
373 | Http_types.Param_not_found attr_name ->
374 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
376 return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
379 (* UWOBO's startup *)
381 (* (1) system logger *)
383 debug_print (sprintf "Logging to file %s" logfile);
384 open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
387 new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
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
399 | Some pid -> Unix.kill pid Sys.sigterm);
400 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
402 close_out logger_outchan
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 *)
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 *)
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
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 *)
437 output_string res_pipe "UWOBOmaster: Hello, world!\n";
439 raise Restart_HTTP_daemon
440 | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
442 | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
444 Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
447 let logger = new Uwobo_logger.processingLogger () in
449 (fun binding -> (* add a <key, stylesheet> binding *)
450 let pieces = Pcre.split ~pat:"," binding in
453 logger#log (sprintf "adding binding <%s,%s>" key style);
454 veillogger#clearMsgs;
456 veillogger#clearMsgs;
457 styles#add key style;
458 log_libxslt_msgs logger veillogger;
460 logger#log (Printexc.to_string e))
461 | _ -> logger#log (sprintf "invalid binding %s" binding))
463 output_string res_pipe logger#asHtml;
465 raise Restart_HTTP_daemon
466 | line when Pcre.pmatch ~rex:remove_cmd_RE line -> (* /remove *)
468 let arg = Pcre.replace ~rex:remove_cmd_RE line in
469 let logger = new Uwobo_logger.processingLogger () in
470 veillogger#clearMsgs;
473 styles#remove (fun () -> styles#removeAll) styles#keys
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 *)
480 let arg = Pcre.replace ~rex:reload_cmd_RE line in
481 let logger = new Uwobo_logger.processingLogger () in
482 veillogger#clearMsgs;
485 styles#reload (fun () -> styles#reloadAll) styles#keys
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))
493 with Restart_HTTP_daemon ->
494 close_in cmd_pipe; (* these calls close also fds *)
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 :-("
512 (* daemon initialization *)
514 Sys.catch_break true;
516 with Sys.Break -> () (* 'die_nice' registered with at_exit *)