]> matita.cs.unibo.it Git - helm.git/blob - helm/uwobo/uwobo.ml
* added external documentation in tex format
[helm.git] / helm / uwobo / uwobo.ml
1 (*
2  * Copyright (C) 2003:
3  *    Stefano Zacchiroli <zack@cs.unibo.it>
4  *    for the HELM Team http://helm.cs.unibo.it/
5  *
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.
9  *
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.
14  *
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.
19  *
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,
23  *  MA  02111-1307, USA.
24  *
25  *  For details, see the HELM World-Wide-Web page,
26  *  http://helm.cs.unibo.it/
27  *)
28
29 open Printf;;
30 open Uwobo_common;;
31
32  (* debugging settings *)
33 let debug = false ;;
34 let debug_level = `Notice ;;
35 let debug_print s = if debug then prerr_endline s ;;
36 Http_common.debug := false ;;
37
38 let configuration_file = "/projects/helm/etc/uwobo.conf.xml";;
39
40   (* First of all we load the configuration *)
41 let _ =
42   Helm_registry.load_from configuration_file
43 ;;
44
45 let save_configuration () =
46   if not (Helm_registry.has "uwobo.cloned") then
47     Helm_registry.save_to configuration_file
48 ;;
49
50   (* other settings *)
51 let daemon_name = "UWOBO OCaml" ;;
52 let default_media_type = "text/html" ;;
53 let default_encoding = "utf8" ;;
54
55 let get_media_type props =
56  try
57   List.assoc "media-type" props
58  with
59   Not_found -> default_media_type
60 ;;
61
62 let get_encoding props =
63  try
64   List.assoc "encoding" props
65  with
66   Not_found -> default_encoding
67 ;;
68
69 let string_of_param_option (req: Http_types.request) name =
70   try
71     req#param name
72   with
73       Http_types.Param_not_found _ -> "#"
74
75 let string_option_of_string =
76   function
77       "#" -> None
78     | s -> Some s
79
80 let port = Helm_registry.get_int "uwobo.port";;
81
82 let logfilename_of_port port =
83  let basename = Helm_registry.get "uwobo.log_basename" in
84  let extension = Helm_registry.get "uwobo.log_extension" in
85   basename ^ "_" ^ string_of_int port ^ extension
86 ;;
87
88 let logfile = logfilename_of_port port;;
89 let logfile_perm = 0o640 ;;
90
91 let respond_html body outchan =
92   Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
93 ;;
94
95   (** perform an 'action' that can be applied to a list of keys or, if no keys
96   was given, to all keys *)
97 let act_on_keys
98   keys_param styles logger per_key_action all_keys_action all_keys logmsg
99 =
100   let keys =
101     try
102       Pcre.split ~pat:"," keys_param
103     with Http_types.Param_not_found _ -> []
104   in
105   match keys with
106   | [] -> (* no key provided, act on all stylesheets *)
107       logger#log (sprintf "%s all stylesheets (keys = %s) ..."
108         logmsg (String.concat ", " all_keys));
109       (try all_keys_action () with e -> logger#log (Printexc.to_string e));
110       logger#log (sprintf "Done! (all stylesheets)")
111   | keys ->
112       List.iter
113         (fun key -> (* act on a single stylesheet *)
114           logger#log (sprintf "%s stylesheet %s" logmsg key);
115           (try per_key_action key with e -> logger#log (Printexc.to_string e));
116           logger#log (sprintf "Done! (stylesheet %s)" key))
117         keys
118 ;;
119
120   (** parse parameters for '/apply' action *)
121 let parse_apply_params =
122   let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
123   let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
124   let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
125   List.fold_left
126     (fun (old_params, old_properties) (name, value) ->
127       match name with
128       | name when is_global_param name ->
129           let name = Pcre.replace ~pat:"^param\\." name in
130           ((fun x -> (old_params x) @ [name, value]), old_properties)
131       | name when is_local_param name ->
132           let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
133           let (key, name) = (pieces.(1), pieces.(2)) in
134           ((function
135             | x when x = key -> [name, value] @ (old_params x)
136             | x -> old_params x),
137            old_properties)
138       | name when is_property name ->
139           let name = Pcre.replace ~pat:"^prop\\." name in
140           (old_params, ((name, value) :: old_properties))
141       | _ -> (old_params, old_properties))
142     ((fun _ -> []), []) (* no parameters, no properties *)
143 ;;
144
145   (** Parse libxslt's message modes for error and debugging messages. Default is
146   to ignore mesages of both kind *)
147 let parse_libxslt_msgs_mode (req: Http_types.request) =
148   ((try
149     (match req#param "errormode" with
150     | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
151     | s when String.lowercase s = "comment" -> LibXsltMsgComment
152     | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
153     | err ->
154         raise (Uwobo_failure
155           (sprintf
156             "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
157             err "errormode" "ignore" "comment")))
158   with Http_types.Param_not_found _ -> LibXsltMsgIgnore),
159   (try
160     (match req#param "debugmode" with
161     | s when String.lowercase s = "ignore" -> LibXsltMsgIgnore
162     | s when String.lowercase s = "comment" -> LibXsltMsgComment
163     | s when String.lowercase s = "embed" -> LibXsltMsgEmbed
164     | err ->
165         raise (Uwobo_failure
166           (sprintf
167             "Unknown value '%s' for parameter '%s', use one of '%s' or '%s'"
168             err "debugmode" "ignore" "comment")))
169   with Http_types.Param_not_found _ -> LibXsltMsgIgnore))
170 ;;
171
172   (** send ~cmd (without trailing "\n"!) through ~cmd_pipe, then wait for answer
173   on ~res_pipe (with a timeout of 60 seconds) and send over outchan data
174   received from ~res_pipe *)
175 let short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan =
176 (*   debug_print (sprintf "Sending command '%s' to grandparent ..." cmd); *)
177   output_string cmd_pipe (cmd ^ "\n");  (* send command to grandfather *)
178   flush cmd_pipe;
179   let res_pipe_fd = Unix.descr_of_in_channel res_pipe in
180   let (read_fds, _, _) =  (* wait for an answer *)
181     Unix.select [res_pipe_fd] [] [] 60.0
182   in
183   (match read_fds with
184   | [fd] when fd = res_pipe_fd -> (* send answer to http client *)
185       Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
186       Http_daemon.send_header "Content-Type" "text/html" outchan;
187       Http_daemon.send_CRLF outchan;
188       (try
189         while true do
190           output_string outchan ((input_line res_pipe) ^ "\n")
191         done
192       with End_of_file -> flush outchan)
193   | _ ->  (* no answer received from grandfather *)
194       return_error "Timeout!" outchan)
195 ;;
196
197 let (add_cmd_RE, remove_cmd_RE, reload_cmd_RE, kill_cmd_RE,
198      createprofile_cmd_RE, removeprofile_cmd_RE, setprofileparam_cmd_RE,
199      setpassword_cmd_RE, setpermission_cmd_RE) =
200   (Pcre.regexp "^add ", Pcre.regexp "^remove ", Pcre.regexp "^reload ",
201    Pcre.regexp "^kill", Pcre.regexp "^createprofile ", Pcre.regexp "^removeprofile ",
202    Pcre.regexp "^setprofileparam ", Pcre.regexp "^setpassword ", Pcre.regexp "^setpermission ")
203 ;;
204
205   (** raised by child processes when HTTP daemon process have to be restarted *)
206 exception Restart_HTTP_daemon ;;
207
208   (** log a list of libxslt's messages using a processing logger *)
209 let log_libxslt_msgs logger libxslt_logger =
210   List.iter
211     (function
212       | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
213       | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
214     libxslt_logger#msgs
215 ;;
216
217   (* LibXSLT logger *)
218 let veillogger = new Uwobo_common.libXsltLogger ;;
219
220   (* start_new_session cmd_pipe_exit res_pipe_entrance outchan port logfile
221   @param cmd_pipe Pipe to be closed before forking
222   @param res_pipe Pipe to be closed before forking
223   @param outchan  To be closed before forking
224   @param port The port to be used
225   @param logfile The logfile to redirect the stdout and sterr to
226   *)
227   (* It can raise Failure "Connection refused" *)
228   (* It can raise Failure "Port already in use" *)
229 let start_new_session cmd_pipe res_pipe outchan port logfile =
230  (* Let's check that the port is free *)
231  (try
232    ignore
233     (Http_client.http_get
234       ("http://127.0.0.1:" ^ string_of_int port ^ "/help")) ;
235    raise (Failure "Port already in use")
236   with
237    Unix.Unix_error (Unix.ECONNREFUSED, _, _) -> ()
238  ) ;
239  match Unix.fork () with
240     0 ->
241       Unix.handle_unix_error
242        (function () ->
243          (* 1. We close all the open pipes to avoid duplicating them *)
244          Unix.close (Unix.descr_of_out_channel cmd_pipe) ;
245          Unix.close (Unix.descr_of_in_channel res_pipe) ;
246          Unix.close (Unix.descr_of_out_channel outchan) ;
247          (* 2. We redirect stdout and stderr to the logfile *)
248          Unix.close Unix.stdout ;
249          assert
250           (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
251             0o664 = Unix.stdout) ;
252          Unix.close Unix.stderr ;
253          assert
254           (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
255             0o664 = Unix.stderr) ;
256          prerr_endline "***** Starting a new session" ;
257
258          (* 3. We set up a new environment *)
259          let environment =
260           (* Here I am loosing the current value of port_env_var; *)
261           (* this should not matter                               *)
262           Unix.putenv "uwobo__port" (string_of_int port) ;
263           Unix.putenv "uwobo__cloned" "1" ;
264           Unix.environment ()
265          in
266          (* 4. We exec a new copy of uwobo *)
267          Unix.execve Sys.executable_name [||] environment ; 
268          (* It should never reach this point *)
269          assert false
270        ) ()
271   | child when child > 0 ->
272      (* let's check if the new UWOBO started correctly *)
273      Unix.sleep 5 ;
274      (* It can raise Failure "Connection refused" *)
275      (try
276        ignore
277          (Http_client.http_get
278            ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
279      with Unix.Unix_error (Unix.ECONNREFUSED, _, _) ->
280        raise (Failure "Connection refused"))
281   | _ -> failwith "Can't fork :-("
282 ;;
283
284   (* request handler action
285   @param syslogger Uwobo_logger.sysLogger instance used for logginf
286   @param styles Uwobo_styles.styles instance which keeps the stylesheets list
287   @param cmd_pipe output _channel_ used to _write_ update messages
288   @param res_pipe input _channel_ used to _read_ grandparent results
289   @param req http request instance
290   @param outchan output channel connected to http client
291   *)
292 let callback
293   ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
294   =
295   try
296     syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
297     syslogger#log `Debug (sprintf "Received request: %s" req#path);
298     (match req#path with
299     | "/add" ->
300         (let bindings = req#paramAll "bind" in
301         if bindings = [] then
302           return_error "No [key,stylesheet] binding provided" outchan
303         else begin
304           let cmd = sprintf "add %s" (String.concat ";" bindings) in
305           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
306         end)
307     | "/kill" ->
308         let logger = new Uwobo_logger.processingLogger () in
309          logger#log "Exiting" ;
310          respond_html logger#asHtml outchan ;
311          let cmd = "kill" in
312           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
313     | "/newsession" ->
314         let logger = new Uwobo_logger.processingLogger () in
315         let port = int_of_string (req#param "port") in
316         let logfile = logfilename_of_port port in
317         (try
318           start_new_session cmd_pipe res_pipe outchan port logfile ;
319           logger#log (sprintf "New session started: port = %d" port) ;
320           respond_html logger#asHtml outchan
321          with
322             Failure "int_of_string" ->
323              logger#log (sprintf "Invalid port number") ;
324              respond_html logger#asHtml outchan
325           | Failure "Port already in use" ->
326              Uwobo_common.return_error "port already in use" outchan
327           | Failure "Connection refused" ->
328              let log = ref [] in
329               (try
330                 let ch = open_in logfile in
331                  while true do log := (input_line ch ^ "\n") :: !log ; done
332                with
333                   Sys_error _
334                 | End_of_file -> ()
335               ) ;
336               let rec get_last_lines acc =
337                function
338                   (n,he::tl) when n > 0 ->
339                     get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
340                 | _ -> acc
341               in
342                (* we just show the last 10 lines of the log file *)
343                let msg =
344                 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
345                  get_last_lines "" (10,!log)
346                in
347                 Uwobo_common.return_error "daemon not initialized"
348                  ~body:msg outchan)
349     | "/remove" ->
350           let cmd = sprintf "remove %s" (req#param "keys") in
351           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
352     | "/reload" ->
353           let cmd = sprintf "reload %s" (req#param "keys") in
354           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
355     | "/list" ->
356         (let logger = new Uwobo_logger.processingLogger () in
357         (match styles#list with
358         | [] -> logger#log "No stylesheets loaded (yet)!"
359         | l ->
360             logger#log "Stylesheets list:";
361             List.iter (fun s -> logger#log s) l);
362         respond_html logger#asHtml outchan)
363     | "/listprofiles" ->
364         let profile_list = Uwobo_profiles.list () in
365         respond_html ("<html><body><ul>" ^ String.concat "" (List.map (fun s -> "<li>" ^ s ^ "</li>") profile_list) ^ "</ul></body></html>") outchan
366     | "/createprofile" ->
367         let cmd = sprintf "createprofile %s,%s,%s,%s,%s,%s,%s" 
368                     (string_of_param_option req "id")
369                     (string_of_param_option req "orig")
370                     (string_of_param_option req "origpassword")
371                     (string_of_param_option req "readperm")
372                     (string_of_param_option req "writeperm")
373                     (string_of_param_option req "adminperm")
374                     (string_of_param_option req "password")
375         in
376           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
377     | "/removeprofile" -> 
378         let cmd = sprintf "removeprofile %s,%s" 
379                     (req#param "id")
380                     (string_of_param_option req "password")
381         in
382           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
383     | "/setparam" ->
384         let cmd = sprintf "setprofileparam %s,%s,%s,%s" 
385                     (string_of_param_option req "id")
386                     (string_of_param_option req "password")
387                     (req#param "key")
388                     (string_of_param_option req "value")
389         in
390           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
391     | "/setpassword" ->
392         let cmd = sprintf "setpassword %s,%s,%s" 
393                     (req#param "id")
394                     (string_of_param_option req "password")
395                     (string_of_param_option req "oldpassword")
396         in
397           short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
398     | "/setpermission" ->
399         begin
400           match req#param "for" with
401               "read"
402             | "write"
403             | "admin" as forwhat ->
404                 let cmd = sprintf "setpermission %s,%s,%s,%s" 
405                             (req#param "id")
406                             (string_of_param_option req "password")
407                             forwhat
408                             (req#param "value")
409                 in
410                   short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
411             | _ -> Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) outchan
412         end
413     | "/getparams" ->
414         let pid = req#param "id" in
415         let password = try Some (req#param "password") with _ -> None in
416         let res = Uwobo_profiles.get_params pid ?password () in
417         respond_html
418          ("<html><body><ul>" ^
419           String.concat "" (List.map (fun k,v -> "<li>" ^ k ^ " = " ^ v  ^ "</li>") res) ^
420           "</ul></body></html>") outchan
421     | "/getparam" ->
422         let pid = req#param "id" in
423         let password = try Some (req#param "password") with _ -> None in
424         let key = req#param "key" in
425         let value = Uwobo_profiles.get_param pid ?password ~key () in
426         respond_html ("<html><body>" ^ value ^ "</body></html>") outchan
427     | "/getpermission" ->
428         let pid = req#param "id" in
429         let password = try Some (req#param "password") with _ -> None in
430         let forwhat =
431          match req#param "for" with
432             "read" -> Some `Read
433           | "write" -> Some `Write
434           | "admin" -> Some `Admin
435           | _ -> None
436         in
437          begin
438           match forwhat with
439              Some forwhat ->
440               let value = Uwobo_profiles.get_permission pid ?password forwhat in
441               respond_html ("<html><body>" ^ (if value then "true" else "false") ^ "</body></html>") outchan
442            | None -> Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) outchan ;
443          end
444     | "/apply" ->
445         let logger = new Uwobo_logger.processingLogger () in
446         veillogger#clearMsgs;
447         let profile = try Some (req#param "profile") with _ -> None in
448         let password = try Some (req#param "password") with _ -> None in
449         let xmluri = req#param "xmluri" in
450         let keys = Pcre.split ~pat:"," (req#param "keys") in
451         (* notation: "local" parameters are those defined on a per-stylesheet
452         pasis (i.e. param.key.param=value), "global" parameters are those
453         defined for all stylesheets (i.e. param.param=value) *)
454         let (user_params, props) = parse_apply_params req#params in
455         let profile_params =
456          match profile with
457             None -> []
458           | Some profile -> Uwobo_profiles.get_params profile ?password () in
459         let params =
460          (* user provided parameters override the profile parameters *)
461          let is_global_param x = Pcre.pmatch ~pat:"^(\\.[^.]+){1}$" ("." ^ x) in
462          let is_local_param x = Pcre.pmatch ~pat:"^(\\.[^.]+){2}$" ("." ^ x) in
463          let add key value params =
464           if List.mem_assoc key params then params else params @ [key,value]
465          in
466           List.fold_left
467             (fun old_params (name, value) ->
468               match name with
469               | name when is_global_param name ->
470                  (fun x -> add name value (old_params x))
471               | name when is_local_param name ->
472                  let pieces = Pcre.extract ~pat:"^([^.]+)\\.(.*)" name in
473                  let (key, name) = (pieces.(1), pieces.(2)) in
474                   (function
475                     | x when x = key -> add name value (old_params x)
476                     | x -> old_params x)
477               | _ -> assert false)
478             user_params profile_params
479         in
480         let (libxslt_errormode, libxslt_debugmode) =
481           parse_libxslt_msgs_mode req
482         in
483         syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
484         let domImpl = Gdome.domImplementation () in
485         let input = domImpl#createDocumentFromURI ~uri:xmluri () in
486         syslogger#log `Debug "Applying stylesheet chain ...";
487         (try
488           let (write_result, media_type, encoding) = (* out_channel -> unit *)
489             Uwobo_engine.apply
490               ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
491               ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
492               input
493           in
494           let content_type = (* value of Content-Type HTTP response header *)
495             sprintf "%s; charset=%s"
496               (match media_type with None -> get_media_type props | Some t -> t)
497               (match encoding with None -> get_encoding props | Some e -> e)
498           in
499           syslogger#log `Debug
500             (sprintf "sending output to client (Content-Type: %s)...."
501               content_type);
502           Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
503           Http_daemon.send_header "Content-Type" content_type outchan;
504           Http_daemon.send_CRLF outchan;
505           write_result outchan
506         with Uwobo_failure errmsg ->
507           return_error
508             ("Stylesheet chain application failed: " ^ errmsg)
509             ~body: ("<h2>LibXSLT's messages:</h2>" ^
510               String.concat "<br />\n"
511                 (List.map string_of_xslt_msg veillogger#msgs))
512             outchan)
513     | "/help" -> respond_html usage_string outchan
514     | invalid_request ->
515         Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) outchan);
516     syslogger#log `Debug (sprintf "%s done!" req#path);
517   with
518   | Http_types.Param_not_found attr_name ->
519       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
520   | exc ->
521       return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
522 ;;
523
524   (* UWOBO's startup *)
525 let main () =
526     (* (1) system logger *)
527   let logger_outchan =
528    debug_print (sprintf "Logging to file %s" logfile);
529    open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
530   in
531   let syslogger =
532     new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
533   in
534   syslogger#enable;
535     (* (2) stylesheets list *)
536   let styles = new Uwobo_styles.styles in
537     (* (3) clean up actions *)
538   let last_process = ref true in
539   let http_child = ref None in
540   let die_nice () = (** at_exit callback *)
541     if !last_process then begin
542       (match !http_child with
543       | None -> ()
544       | Some pid -> Unix.kill pid Sys.sigterm);
545       syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
546       syslogger#disable;
547       close_out logger_outchan
548     end
549   in
550   at_exit die_nice;
551   ignore (Sys.signal Sys.sigterm
552     (Sys.Signal_handle (fun _ -> raise Sys.Break)));
553   syslogger#log `Notice
554     (sprintf "%s started and listening on port %d" daemon_name port);
555   syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
556   Unix.putenv "http_proxy" "";  (* reset http_proxy to avoid libxslt problems *)
557   while true do
558     let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
559     let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
560     match Unix.fork () with
561     | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
562         http_child := Some child;
563         let stop_http_daemon () =  (* kill child *)
564           debug_print (sprintf "UWOBOmaster: killing pid %d" child);
565           Unix.kill child Sys.sigterm;  (* kill child ... *)
566           ignore (Unix.waitpid [] child);  (* ... and its zombie *)
567         in
568         Unix.close cmd_pipe_entrance;
569         Unix.close res_pipe_exit;
570         let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
571         let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
572         (try
573           while true do
574             (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
575             child process has been killed *)
576             debug_print "UWOBOmaster: waiting for commands ...";
577             let cmd = input_line cmd_pipe in
578             debug_print (sprintf "UWOBOmaster: received %s command" cmd);
579             (match cmd with  (* command from grandchild *)
580             | "test" ->
581                 stop_http_daemon ();
582                 output_string res_pipe "UWOBOmaster: Hello, world!\n";
583                 flush res_pipe;
584                 raise Restart_HTTP_daemon
585             | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
586                 exit 0
587             | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
588                 let bindings =
589                   Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
590                 in
591                 stop_http_daemon ();
592                 let logger = new Uwobo_logger.processingLogger () in
593                 List.iter
594                   (fun binding -> (* add a <key, stylesheet> binding *)
595                     let pieces = Pcre.split ~pat:"," binding in
596                     match pieces with
597                     | [key; style] ->
598                         logger#log (sprintf "adding binding <%s,%s>" key style);
599                         veillogger#clearMsgs;
600                         (try
601                           veillogger#clearMsgs;
602                           styles#add key style;
603                           log_libxslt_msgs logger veillogger;
604                         with e ->
605                           logger#log (Printexc.to_string e))
606                     | _ -> logger#log (sprintf "invalid binding %s" binding))
607                   bindings;
608                 output_string res_pipe logger#asHtml;
609                 flush res_pipe;
610                 raise Restart_HTTP_daemon
611             | line when Pcre.pmatch ~rex:remove_cmd_RE line ->  (* /remove *)
612                 stop_http_daemon ();
613                 let arg = Pcre.replace ~rex:remove_cmd_RE line in
614                 let logger = new Uwobo_logger.processingLogger () in
615                 veillogger#clearMsgs;
616                 act_on_keys
617                   arg styles logger
618                   styles#remove (fun () -> styles#removeAll) styles#keys
619                   "removing";
620                 log_libxslt_msgs logger veillogger;
621                 output_string res_pipe (logger#asHtml);
622                 raise Restart_HTTP_daemon
623             | line when Pcre.pmatch ~rex:reload_cmd_RE line ->  (* /reload *)
624                 stop_http_daemon ();
625                 let arg = Pcre.replace ~rex:reload_cmd_RE line in
626                 let logger = new Uwobo_logger.processingLogger () in
627                 veillogger#clearMsgs;
628                 act_on_keys
629                   arg styles logger
630                   styles#reload (fun () -> styles#reloadAll) styles#keys
631                   "reloading";
632                 output_string res_pipe (logger#asHtml);
633                 raise Restart_HTTP_daemon
634             | line when Pcre.pmatch ~rex:createprofile_cmd_RE line -> (* /createprofile *)
635               stop_http_daemon ();
636               let params =
637                 List.map string_option_of_string (Pcre.split ~pat:"," (Pcre.replace ~rex:createprofile_cmd_RE line))
638               in
639                 begin
640                   match params with
641                       [id; clone; clone_password; read_perm; write_perm; admin_perm; password] ->
642                         let bool_option_of_string_option =
643                           function
644                               Some "true" -> Some true
645                             | Some _ -> Some false
646                             | None -> None
647                         in
648                         let pid =
649                           Uwobo_profiles.create
650                             ?id
651                             ?clone
652                             ?clone_password 
653                             ?read_perm:(bool_option_of_string_option read_perm)
654                             ?write_perm:(bool_option_of_string_option write_perm)
655                             ?admin_perm:(bool_option_of_string_option admin_perm)
656                             ?password
657                             ()
658                         in
659                           save_configuration () ;
660                           output_string res_pipe ("Profile " ^ pid ^ " created. Hi " ^ pid) ;
661                           raise Restart_HTTP_daemon
662                     | _ -> assert false
663                 end
664             | line when Pcre.pmatch ~rex:removeprofile_cmd_RE line -> (* /removeprofile *)
665               stop_http_daemon ();
666               let pid, password =
667                 match Pcre.split ~pat:"," (Pcre.replace ~rex:removeprofile_cmd_RE line) with
668                     [pid; password] -> pid, (string_option_of_string password)
669                   | _ -> assert false
670               in
671                 Uwobo_profiles.remove pid ?password () ;
672                 save_configuration () ;
673                 output_string res_pipe "Done" ;
674                 raise Restart_HTTP_daemon
675             | line when Pcre.pmatch ~rex:setprofileparam_cmd_RE line -> (* /setprofileparam *)
676               stop_http_daemon ();
677               let pid, password, key, value =
678                 match Pcre.split ~pat:"," (Pcre.replace ~rex:setprofileparam_cmd_RE line) with
679                     [pid; password; key; value] ->
680                       pid, (string_option_of_string password), key, (string_option_of_string value)
681                   | _ -> assert false
682               in
683                 Uwobo_profiles.set_param pid ?password ~key ~value () ;
684                 save_configuration () ;
685                 output_string res_pipe "Done" ;
686                 raise Restart_HTTP_daemon
687             | line when Pcre.pmatch ~rex:setpassword_cmd_RE line -> (* /setpassword *)
688               stop_http_daemon ();
689               let pid, old_password, password =
690                 match Pcre.split ~pat:"," (Pcre.replace ~rex:setpassword_cmd_RE line) with
691                     [pid; old_password; password] ->
692                       pid, (string_option_of_string old_password), (string_option_of_string password)
693                   | _ -> assert false
694               in
695                 Uwobo_profiles.set_password pid ?old_password password ;
696                 save_configuration () ;
697                 output_string res_pipe "Done" ;
698                 raise Restart_HTTP_daemon
699             | line when Pcre.pmatch ~rex:setpermission_cmd_RE line -> (* /setpermission *)
700               stop_http_daemon ();
701               let permission_of_string =
702                 function
703                     "read" -> `Read
704                   | "write" -> `Write
705                   | "admin" -> `Admin
706                   | _ -> assert false
707               and bool_of_string s = ("public" = s) || ("true" = s)
708               in
709               let pid, password, forwhat, value =
710                 match Pcre.split ~pat:"," (Pcre.replace ~rex:setpermission_cmd_RE line) with
711                     [pid; password; forwhat; value] ->
712                       pid, (string_option_of_string password), (permission_of_string forwhat), (bool_of_string value)
713                   | _ -> assert false
714               in
715                 Uwobo_profiles.set_permission pid ?password forwhat value ;
716                 save_configuration () ;
717                 output_string res_pipe "Done" ;
718                 raise Restart_HTTP_daemon
719             | cmd ->  (* invalid interprocess command received *)
720                 syslogger#log `Warning
721                   (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
722           done
723         with
724            Restart_HTTP_daemon ->
725             close_in cmd_pipe;  (* these calls close also fds *)
726             close_out res_pipe
727          | e -> (* Should we return a 404 error here? Maybe... (how?) *)
728             output_string res_pipe (Printexc.to_string e);
729             close_in cmd_pipe;  (* these calls close also fds *)
730             close_out res_pipe)
731     | 0 ->  (* (5) child: serve http requests *)
732         Unix.close cmd_pipe_exit;
733         Unix.close res_pipe_entrance;
734         last_process := false;
735         let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
736         let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
737         debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
738           (* next invocation doesn't return, process will keep on serving HTTP
739           requests until it will get killed by father *)
740         Http_daemon.start'~port ~mode:`Fork
741           (callback ~syslogger ~styles ~cmd_pipe ~res_pipe ())
742     | _ (* < 0 *) ->  (* fork failed :-((( *)
743         failwith "Can't fork :-("
744   done
745 ;;
746
747   (* daemon initialization *)
748 try
749   Sys.catch_break true;
750   main ()
751 with Sys.Break -> ()  (* 'die_nice' registered with at_exit *)
752 ;;
753