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;;
37 let logfile = Some "uwobo.log";; (* relative to execution dir *)
38 let logfile_perm = 0o640;;
41 let daemon_name = "UWOBO OCaml";;
42 let default_port = 58080;;
43 let port_env_var = "UWOBO_PORT";;
44 let default_media_type = "text/html";;
45 let default_encoding = "utf8";;
48 int_of_string (Sys.getenv port_env_var)
50 | Not_found -> default_port
51 | Failure "int_of_string" ->
52 prerr_endline "Warning: invalid port, reverting to default";
55 (** perform an 'action' that can be applied to a list of keys or, if no keys
56 was given, to all keys *)
57 let act_on_keys keys_param styles outchan per_key_action all_keys_action logmsg
59 let log = new Uwobo_logger.processingLogger () in
62 Pcre.split ~pat:"," keys_param
63 with Http_types.Param_not_found _ -> []
66 | [] -> (* no key provided, act on all stylesheets *)
67 log#log "reloading all stylesheets ...";
68 (try all_keys_action () with e -> log#log (Printexc.to_string e))
71 (fun key -> (* act on a single stylesheet *)
72 log#log (sprintf "%s stylesheet %s" logmsg key);
73 (try per_key_action key with e -> log#log (Printexc.to_string e)))
75 output_string outchan log#asHtml;
79 (** parse parameters for '/apply' action *)
80 let parse_apply_params =
81 let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
82 let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
83 let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
85 (fun (old_params, old_properties) (name, value) ->
87 | name when is_global_param name ->
88 let name = Pcre.replace ~pat:"^param\\." name in
89 ((fun x -> (old_params x) @ [name, value]), old_properties)
90 | name when is_local_param name ->
91 let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
92 let (key, name) = (pieces.(1), pieces.(2)) in
94 | x when x = key -> [name, value] @ (old_params x)
97 | name when is_property name ->
98 let name = Pcre.replace ~pat:"^prop\\." name in
99 (old_params, ((name, value) :: old_properties))
100 | _ -> (old_params, old_properties))
101 ((fun _ -> []), []) (* no parameters, no properties *)
104 (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
105 on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
106 received from ~res_pipe *)
107 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
108 debug_print (sprintf "Sending command '%s' to grandparent ..." cmd);
109 output_string cmd_pipe (cmd ^ "\n"); (* send command to grandfather *)
111 let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
112 let (read_fds, _, _) = (* wait for an answer *)
113 Unix.select [res_pipe_fd] [] [] 60.0
116 | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
117 Http_daemon.send_basic_headers ~code:200 outchan;
118 Http_daemon.send_CRLF outchan;
121 output_string outchan ((input_line res_pipe) ^ "\n")
123 with End_of_file -> flush outchan)
124 | _ -> (* no answer received from grandfather *)
125 return_error "Timeout!" outchan)
128 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE) =
129 (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ")
132 exception Restart_HTTP_daemon;;
135 @param syslogger Uwobo_logger.sysLogger instance used for logginf
136 @param styles Uwobo_styles.styles instance which keeps the stylesheets list
137 @param cmd_pipe output _channel_ used to _write_ update messages
138 @param res_pipe input _channel_ used to _read_ grandparent results
139 @param req http request instance
140 @param outchan output channel connected to http client
143 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
146 syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
147 syslogger#log `Debug (sprintf "Received request: %s" req#path);
150 (let bindings = req#paramAll "bind" in
151 if bindings = [] then
152 return_error "No [key,stylesheet] binding provided" outchan
154 let cmd = sprintf "add %s" (String.concat ";" bindings) in
155 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
158 let cmd = sprintf "remove %s" (req#param "keys") in
159 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
161 let cmd = sprintf "reload %s" (req#param "keys") in
162 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
164 (let log = new Uwobo_logger.processingLogger () in
165 log#log "Stylesheet list:";
166 List.iter (fun s -> log#log s) styles#list;
167 Http_daemon.respond ~body:log#asHtml outchan)
169 let logger = new Uwobo_logger.processingLogger () in
170 let xmluri = req#param "xmluri" in
171 let keys = Pcre.split ~pat:"," (req#param "keys") in
172 (* notation: "local" parameters are those defined on a per-stylesheet
173 pasis (i.e. param.key.param=value), "global" parameters are those
174 defined for all stylesheets (i.e. param.param=value) *)
175 let (params, props) = parse_apply_params req#params in
176 syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
177 let domImpl = Gdome.domImplementation () in
178 let input = domImpl#createDocumentFromURI ~uri:xmluri () in
179 syslogger#log `Debug "Applying stylesheet chain ...";
181 let (write_result, media_type, encoding) = (* out_channel -> unit *)
182 let res = Uwobo_engine.apply
183 ~logger:syslogger ~styles ~keys ~input ~params ~props in
186 let content_type = (* value of Content-Type HTTP response header *)
187 sprintf "%s; charset=%s"
188 (match media_type with None -> default_media_type | Some t -> t)
189 (match encoding with None -> default_encoding | Some e -> e)
192 (sprintf "sending output to client (Content-Type: %s)...."
194 Http_daemon.send_basic_headers ~code:200 outchan;
195 Http_daemon.send_header "Content-Type" content_type outchan;
196 Http_daemon.send_CRLF outchan;
198 with Uwobo_failure errmsg ->
200 (sprintf "Stylesheet chain application failed: %s" errmsg)
203 output_string cmd_pipe "test\n";
206 (sprintf "Grandchild: grandparent said '%s'" (input_line res_pipe));
207 Http_daemon.respond ~body:usage_string outchan
209 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
210 syslogger#log `Debug (sprintf "%s done!" req#path);
212 | Http_types.Param_not_found attr_name ->
213 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
215 return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
218 (* UWOBO's startup *)
220 (* (1) system logger *)
225 open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm f
228 new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
231 (* (2) stylesheets list *)
232 let styles = new Uwobo_styles.styles in
233 (* (3) clean up actions *)
234 let last_process = ref true in
235 let http_child = ref None in
236 let die_nice () = (** at_exit callback *)
237 if !last_process then begin
238 (match !http_child with
240 | Some pid -> Unix.kill pid Sys.sigterm);
241 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
243 close_out logger_outchan
247 ignore (Sys.signal Sys.sigterm
248 (Sys.Signal_handle (fun _ -> raise Sys.Break)));
249 syslogger#log `Notice
250 (sprintf "%s started and listening on port %d" daemon_name port);
251 syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
252 Unix.putenv "http_proxy" ""; (* reset http_proxy to avoid libxslt problems *)
254 let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
255 let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
256 match Unix.fork () with
257 | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
258 http_child := Some child;
259 let stop_http_daemon () = (* kill child *)
260 debug_print (sprintf "Grandparent: killing pid %d" child);
261 Unix.kill child Sys.sigterm; (* kill child ... *)
262 debug_print "Grandparent: waiting for its zombie ...";
263 ignore (Unix.waitpid [] child); (* ... and its zombie *)
264 debug_print "Grandparent: murder completed!!!"
266 Unix.close cmd_pipe_entrance;
267 Unix.close res_pipe_exit;
268 let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
269 let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
272 (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
273 child process has been killed *)
274 debug_print "Grandparent: waiting for commands ...";
275 let cmd = input_line cmd_pipe in
276 debug_print (sprintf "Grandparent: received %s command" cmd);
277 (match cmd with (* command from grandchild *)
279 debug_print "Grandparent: Hello, world!";
281 output_string res_pipe "Grandparent: Hello, world!\n";
283 raise Restart_HTTP_daemon
284 | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
286 Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
289 let log = new Uwobo_logger.processingLogger () in
291 (fun binding -> (* add a <key, stylesheet> binding *)
292 let pieces = Pcre.split ~pat:"," binding in
295 log#log (sprintf "adding binding <%s,%s>" key style);
297 styles#add key style;
299 log#log (Printexc.to_string e))
300 | _ -> log#log (sprintf "invalid binding %s" binding))
302 output_string res_pipe log#asHtml;
304 raise Restart_HTTP_daemon
305 | line when Pcre.pmatch ~rex:remove_cmd_RE line -> (* /remove *)
307 let arg = Pcre.replace ~rex:remove_cmd_RE line in
310 styles#remove (fun () -> styles#removeAll)
312 raise Restart_HTTP_daemon
313 | line when Pcre.pmatch ~rex:reload_cmd_RE line -> (* /reload *)
315 let arg = Pcre.replace ~rex:reload_cmd_RE line in
318 styles#reload (fun () -> styles#reloadAll)
320 raise Restart_HTTP_daemon
321 | cmd -> (* invalid interprocess command received *)
322 syslogger#log `Warning
323 (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
325 with Restart_HTTP_daemon ->
326 close_in cmd_pipe; (* these calls close also fds *)
328 | 0 -> (* (5) child: serve http requests *)
329 Unix.close cmd_pipe_exit;
330 Unix.close res_pipe_entrance;
331 last_process := false;
332 let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
333 let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
334 debug_print "Starting HTTP daemon ...";
335 Http_daemon.start'~port ~mode:`Fork
336 (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
337 | _ (* < 0 *) -> (* fork failed :-((( *)
338 failwith "Can't fork :-("
342 (* daemon initialization *)
344 Sys.catch_break true;
346 with Sys.Break -> () (* 'die_nice' registered with at_exit *)