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 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" ;;
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 port =
59 Sys.getenv log_env_var
61 Not_found -> default_log_base_file
63 basename ^ "_" ^ string_of_int port ^ log_extension
65 let logfile = logfilename_of_port port;;
66 let logfile_perm = 0o640 ;;
68 let respond_html body outchan =
69 Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
72 (** perform an 'action' that can be applied to a list of keys or, if no keys
73 was given, to all keys *)
75 keys_param styles logger per_key_action all_keys_action all_keys logmsg
79 Pcre.split ~pat:"," keys_param
80 with Http_types.Param_not_found _ -> []
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)")
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))
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
103 (fun (old_params, old_properties) (name, value) ->
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
112 | x when x = key -> [name, value] @ (old_params x)
113 | x -> old_params x),
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 *)
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) =
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
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),
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
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))
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 *)
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
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;
167 output_string outchan ((input_line res_pipe) ^ "\n")
169 with End_of_file -> flush outchan)
170 | _ -> (* no answer received from grandfather *)
171 return_error "Timeout!" outchan)
174 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE, kill_cmd_RE) =
175 (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ",
179 (** raised by child processes when HTTP daemon process have to be restarted *)
180 exception Restart_HTTP_daemon ;;
182 (** log a list of libxslt's messages using a processing logger *)
183 let log_libxslt_msgs logger libxslt_logger =
186 | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
187 | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
192 let veillogger = new Uwobo_common.libXsltLogger ;;
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
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 =
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) ;
210 (* Let's check that the port is free *)
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")
217 Failure "Connection refused" -> ()
219 match Unix.fork () with
221 Unix.handle_unix_error
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 ;
230 (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
231 0o664 = Unix.stdout) ;
232 Unix.close Unix.stderr ;
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 *)
242 | child when child > 0 ->
243 (* let's check if the new UWOBO started correctly *)
245 (* It can raise Failure "Connection refused" *)
247 (Http_client.Convenience.http_head_message
248 ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
249 | _ -> failwith "Can't fork :-("
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
261 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
264 syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
265 syslogger#log `Debug (sprintf "Received request: %s" req#path);
268 (let bindings = req#paramAll "bind" in
269 if bindings = [] then
270 return_error "No [key,stylesheet] binding provided" outchan
272 let cmd = sprintf "add %s" (String.concat ";" bindings) in
273 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
276 let logger = new Uwobo_logger.processingLogger () in
277 logger#log "Exiting" ;
278 respond_html logger#asHtml outchan ;
280 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
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
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
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" ->
298 let ch = open_in logfile in
299 while true do log := (input_line ch ^ "\n") :: !log ; done
304 let rec get_last_lines acc =
306 (n,he::tl) when n > 0 ->
307 get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
310 (* we just show the last 10 lines of the log file *)
312 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
313 get_last_lines "" (10,!log)
315 Uwobo_common.return_error "daemon not initialized"
318 let cmd = sprintf "remove %s" (req#param "keys") in
319 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
321 let cmd = sprintf "reload %s" (req#param "keys") in
322 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
324 (let logger = new Uwobo_logger.processingLogger () in
325 (match styles#list with
326 | [] -> logger#log "No stylesheets loaded (yet)!"
328 logger#log "Stylesheets list:";
329 List.iter (fun s -> logger#log s) l);
330 respond_html logger#asHtml outchan)
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
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 ...";
348 let (write_result, media_type, encoding) = (* out_channel -> unit *)
350 ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
351 ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
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)
360 (sprintf "sending output to client (Content-Type: %s)...."
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;
366 with Uwobo_failure errmsg ->
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))
373 | "/help" -> respond_html usage_string outchan
375 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
376 syslogger#log `Debug (sprintf "%s done!" req#path);
378 | Http_types.Param_not_found attr_name ->
379 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
381 return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
384 (* UWOBO's startup *)
386 (* (1) system logger *)
388 debug_print (sprintf "Logging to file %s" logfile);
389 open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
392 new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
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
404 | Some pid -> Unix.kill pid Sys.sigterm);
405 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
407 close_out logger_outchan
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 *)
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 *)
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
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 *)
442 output_string res_pipe "UWOBOmaster: Hello, world!\n";
444 raise Restart_HTTP_daemon
445 | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
447 | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
449 Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
452 let logger = new Uwobo_logger.processingLogger () in
454 (fun binding -> (* add a <key, stylesheet> binding *)
455 let pieces = Pcre.split ~pat:"," binding in
458 logger#log (sprintf "adding binding <%s,%s>" key style);
459 veillogger#clearMsgs;
461 veillogger#clearMsgs;
462 styles#add key style;
463 log_libxslt_msgs logger veillogger;
465 logger#log (Printexc.to_string e))
466 | _ -> logger#log (sprintf "invalid binding %s" binding))
468 output_string res_pipe logger#asHtml;
470 raise Restart_HTTP_daemon
471 | line when Pcre.pmatch ~rex:remove_cmd_RE line -> (* /remove *)
473 let arg = Pcre.replace ~rex:remove_cmd_RE line in
474 let logger = new Uwobo_logger.processingLogger () in
475 veillogger#clearMsgs;
478 styles#remove (fun () -> styles#removeAll) styles#keys
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 *)
485 let arg = Pcre.replace ~rex:reload_cmd_RE line in
486 let logger = new Uwobo_logger.processingLogger () in
487 veillogger#clearMsgs;
490 styles#reload (fun () -> styles#reloadAll) styles#keys
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))
498 with Restart_HTTP_daemon ->
499 close_in cmd_pipe; (* these calls close also fds *)
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 :-("
517 (* daemon initialization *)
519 Sys.catch_break true;
521 with Sys.Break -> () (* 'die_nice' registered with at_exit *)