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