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_file = "uwobo.log" ;; (* relative to execution dir *)
41 let default_port = 58080 ;;
42 let port_env_var = "UWOBO_PORT" ;;
43 let default_media_type = "text/html" ;;
44 let default_encoding = "utf8" ;;
46 Some (try Sys.getenv "UWOBO_LOG_FILE" with Not_found -> default_log_file)
48 let logfile_perm = 0o640 ;;
51 int_of_string (Sys.getenv port_env_var)
53 | Not_found -> default_port
54 | Failure "int_of_string" ->
55 prerr_endline "Warning: invalid port, reverting to default";
59 let respond_html body outchan =
60 Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
63 (** perform an 'action' that can be applied to a list of keys or, if no keys
64 was given, to all keys *)
65 let act_on_keys keys_param styles logger per_key_action all_keys_action logmsg
69 Pcre.split ~pat:"," keys_param
70 with Http_types.Param_not_found _ -> []
73 | [] -> (* no key provided, act on all stylesheets *)
74 logger#log (sprintf "%s all stylesheets ..." logmsg);
75 (try all_keys_action () with e -> logger#log (Printexc.to_string e))
78 (fun key -> (* act on a single stylesheet *)
79 logger#log (sprintf "%s stylesheet %s" logmsg key);
80 (try per_key_action key with e -> logger#log (Printexc.to_string e)))
84 (** parse parameters for '/apply' action *)
85 let parse_apply_params =
86 let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
87 let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
88 let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
90 (fun (old_params, old_properties) (name, value) ->
92 | name when is_global_param name ->
93 let name = Pcre.replace ~pat:"^param\\." name in
94 ((fun x -> (old_params x) @ [name, value]), old_properties)
95 | name when is_local_param name ->
96 let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
97 let (key, name) = (pieces.(1), pieces.(2)) in
99 | x when x = key -> [name, value] @ (old_params x)
100 | x -> old_params x),
102 | name when is_property name ->
103 let name = Pcre.replace ~pat:"^prop\\." name in
104 (old_params, ((name, value) :: old_properties))
105 | _ -> (old_params, old_properties))
106 ((fun _ -> []), []) (* no parameters, no properties *)
109 (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
110 on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
111 received from ~res_pipe *)
112 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
113 (* debug_print (sprintf "Sending command '%s' to grandparent ..." cmd); *)
114 output_string cmd_pipe (cmd ^ "\n"); (* send command to grandfather *)
116 let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
117 let (read_fds, _, _) = (* wait for an answer *)
118 Unix.select [res_pipe_fd] [] [] 60.0
121 | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
122 Http_daemon.send_basic_headers ~code:200 outchan;
123 Http_daemon.send_header "Content-Type" "text/html" outchan;
124 Http_daemon.send_CRLF outchan;
127 output_string outchan ((input_line res_pipe) ^ "\n")
129 with End_of_file -> flush outchan)
130 | _ -> (* no answer received from grandfather *)
131 return_error "Timeout!" outchan)
134 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE) =
135 (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ")
138 exception Restart_HTTP_daemon;;
140 (** log a list of libxslt's messages using a processing logger *)
141 let log_libxslt_msgs logger =
144 | Uwobo_styles.LibXsltErrorMsg msg ->
145 logger#logBold ("LibXSLT ERROR: " ^ msg)
146 | Uwobo_styles.LibXsltDebugMsg msg ->
147 logger#logEmph ("LibXSLT DEBUG " ^ msg))
150 (* request handler action
151 @param syslogger Uwobo_logger.sysLogger instance used for logginf
152 @param styles Uwobo_styles.styles instance which keeps the stylesheets list
153 @param cmd_pipe output _channel_ used to _write_ update messages
154 @param res_pipe input _channel_ used to _read_ grandparent results
155 @param req http request instance
156 @param outchan output channel connected to http client
159 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
162 syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
163 syslogger#log `Debug (sprintf "Received request: %s" req#path);
166 (let bindings = req#paramAll "bind" in
167 if bindings = [] then
168 return_error "No [key,stylesheet] binding provided" outchan
170 let cmd = sprintf "add %s" (String.concat ";" bindings) in
171 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
174 let cmd = sprintf "remove %s" (req#param "keys") in
175 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
177 let cmd = sprintf "reload %s" (req#param "keys") in
178 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
180 (let log = new Uwobo_logger.processingLogger () in
181 (match styles#list with
182 | [] -> log#log "No stylesheets loaded (yet)!"
184 log#log "Stylesheets list:";
185 List.iter (fun s -> log#log s) l);
186 respond_html log#asHtml outchan)
188 let logger = new Uwobo_logger.processingLogger () in
189 let xmluri = req#param "xmluri" in
190 let keys = Pcre.split ~pat:"," (req#param "keys") in
191 (* notation: "local" parameters are those defined on a per-stylesheet
192 pasis (i.e. param.key.param=value), "global" parameters are those
193 defined for all stylesheets (i.e. param.param=value) *)
194 let (params, props) = parse_apply_params req#params in
195 syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
196 let domImpl = Gdome.domImplementation () in
197 let input = domImpl#createDocumentFromURI ~uri:xmluri () in
198 syslogger#log `Debug "Applying stylesheet chain ...";
200 let (write_result, media_type, encoding) = (* out_channel -> unit *)
201 let res = Uwobo_engine.apply
202 ~logger:syslogger ~styles ~keys ~input ~params ~props in
205 let content_type = (* value of Content-Type HTTP response header *)
206 sprintf "%s; charset=%s"
207 (match media_type with None -> default_media_type | Some t -> t)
208 (match encoding with None -> default_encoding | Some e -> e)
211 (sprintf "sending output to client (Content-Type: %s)...."
213 Http_daemon.send_basic_headers ~code:200 outchan;
214 Http_daemon.send_header "Content-Type" content_type outchan;
215 Http_daemon.send_CRLF outchan;
217 with Uwobo_failure errmsg ->
219 (sprintf "Stylesheet chain application failed: %s" errmsg)
221 | "/help" -> respond_html usage_string outchan
223 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
224 syslogger#log `Debug (sprintf "%s done!" req#path);
226 | Http_types.Param_not_found attr_name ->
227 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
229 return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
232 (* UWOBO's startup *)
234 (* (1) system logger *)
238 debug_print "Logging to standard error";
241 debug_print (sprintf "Logging to file %s" f);
242 open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm f
245 new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
248 (* (2) stylesheets list *)
249 let styles = new Uwobo_styles.styles in
250 (* (3) clean up actions *)
251 let last_process = ref true in
252 let http_child = ref None in
253 let die_nice () = (** at_exit callback *)
254 if !last_process then begin
255 (match !http_child with
257 | Some pid -> Unix.kill pid Sys.sigterm);
258 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
260 close_out logger_outchan
264 ignore (Sys.signal Sys.sigterm
265 (Sys.Signal_handle (fun _ -> raise Sys.Break)));
266 syslogger#log `Notice
267 (sprintf "%s started and listening on port %d" daemon_name port);
268 syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
269 Unix.putenv "http_proxy" ""; (* reset http_proxy to avoid libxslt problems *)
271 let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
272 let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
273 match Unix.fork () with
274 | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
275 http_child := Some child;
276 let stop_http_daemon () = (* kill child *)
277 debug_print (sprintf "UWOBOmaster: killing pid %d" child);
278 Unix.kill child Sys.sigterm; (* kill child ... *)
279 ignore (Unix.waitpid [] child); (* ... and its zombie *)
281 Unix.close cmd_pipe_entrance;
282 Unix.close res_pipe_exit;
283 let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
284 let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
287 (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
288 child process has been killed *)
289 debug_print "UWOBOmaster: waiting for commands ...";
290 let cmd = input_line cmd_pipe in
291 debug_print (sprintf "UWOBOmaster: received %s command" cmd);
292 (match cmd with (* command from grandchild *)
295 output_string res_pipe "UWOBOmaster: Hello, world!\n";
297 raise Restart_HTTP_daemon
298 | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
300 Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
303 let log = new Uwobo_logger.processingLogger () in
305 (fun binding -> (* add a <key, stylesheet> binding *)
306 let pieces = Pcre.split ~pat:"," binding in
309 log#log (sprintf "adding binding <%s,%s>" key style);
311 log_libxslt_msgs log (styles#add key style)
313 log#log (Printexc.to_string e))
314 | _ -> log#log (sprintf "invalid binding %s" binding))
316 output_string res_pipe log#asHtml;
318 raise Restart_HTTP_daemon
319 | line when Pcre.pmatch ~rex:remove_cmd_RE line -> (* /remove *)
321 let arg = Pcre.replace ~rex:remove_cmd_RE line in
322 let logger = new Uwobo_logger.processingLogger () in
325 (fun key -> log_libxslt_msgs logger (styles#remove key))
326 (fun () -> log_libxslt_msgs logger styles#removeAll)
328 output_string res_pipe (logger#asHtml);
329 raise Restart_HTTP_daemon
330 | line when Pcre.pmatch ~rex:reload_cmd_RE line -> (* /reload *)
332 let arg = Pcre.replace ~rex:reload_cmd_RE line in
333 let logger = new Uwobo_logger.processingLogger () in
336 (fun key -> log_libxslt_msgs logger (styles#reload key))
337 (fun () -> log_libxslt_msgs logger styles#reloadAll)
339 output_string res_pipe (logger#asHtml);
340 raise Restart_HTTP_daemon
341 | cmd -> (* invalid interprocess command received *)
342 syslogger#log `Warning
343 (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
345 with Restart_HTTP_daemon ->
346 close_in cmd_pipe; (* these calls close also fds *)
348 | 0 -> (* (5) child: serve http requests *)
349 Unix.close cmd_pipe_exit;
350 Unix.close res_pipe_entrance;
351 last_process := false;
352 let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
353 let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
354 debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
355 (* next invocation doesn't return, process will keep on serving HTTP
356 requests until it will get killed by father *)
357 Http_daemon.start'~port ~mode:`Fork
358 (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
359 | _ (* < 0 *) -> (* fork failed :-((( *)
360 failwith "Can't fork :-("
364 (* daemon initialization *)
366 Sys.catch_break true;
368 with Sys.Break -> () (* 'die_nice' registered with at_exit *)