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