3 * Stefano Zacchiroli <zack@cs.unibo.it>
4 * for the HELM Team http://helm.cs.unibo.it/
6 * This file is part of HELM, an Hypertextual, Electronic
7 * Library of Mathematics, developed at the Computer Science
8 * Department, University of Bologna, Italy.
10 * HELM is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * HELM is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with HELM; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * For details, see the HELM World-Wide-Web page,
26 * http://helm.cs.unibo.it/
32 (* debugging settings *)
34 let debug_level = `Notice ;;
35 let debug_print s = if debug then prerr_endline s ;;
36 Http_common.debug := false ;;
38 let configuration_file = "/projects/helm/etc/uwobo.conf.xml";;
40 (* First of all we load the configuration *)
42 Helm_registry.load_from configuration_file
45 let save_configuration () =
46 if not (Helm_registry.has "uwobo.cloned") then
47 Helm_registry.save_to configuration_file
51 let daemon_name = "UWOBO OCaml" ;;
52 let default_media_type = "text/html" ;;
53 let default_encoding = "utf8" ;;
55 let get_media_type props =
57 List.assoc "media-type" props
59 Not_found -> default_media_type
62 let get_encoding props =
64 List.assoc "encoding" props
66 Not_found -> default_encoding
69 let string_of_param_option (req: Http_types.request) name =
73 Http_types.Param_not_found _ -> "#"
75 let string_option_of_string =
80 let port = Helm_registry.get_int "uwobo.port";;
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
88 let logfile = logfilename_of_port port;;
89 let logfile_perm = 0o640 ;;
91 let respond_html body outchan =
92 Http_daemon.respond ~body ~headers:["Content-Type", "text/html"] outchan
95 (** perform an 'action' that can be applied to a list of keys or, if no keys
96 was given, to all keys *)
98 keys_param styles logger per_key_action all_keys_action all_keys logmsg
102 Pcre.split ~pat:"," keys_param
103 with Http_types.Param_not_found _ -> []
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)")
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))
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
126 (fun (old_params, old_properties) (name, value) ->
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
135 | x when x = key -> [name, value] @ (old_params x)
136 | x -> old_params x),
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 *)
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
149 let param_value_list =
151 (fun (param, _) -> (is_global_param param) || (is_local_param param))
157 (fun (param, value) -> (Pcre.replace ~pat:"^param\\." param) ^ "=" ^ value)
160 let deserialize_param_list =
163 match Pcre.split ~pat:"=" pv with
165 | [key; value] -> (key, Some value)
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) =
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
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),
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
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))
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 *)
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
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;
213 output_string outchan ((input_line res_pipe) ^ "\n")
215 with End_of_file -> flush outchan)
216 | _ -> (* no answer received from grandfather *)
217 return_error "Timeout!" outchan)
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 ")
229 (** raised by child processes when HTTP daemon process have to be restarted *)
230 exception Restart_HTTP_daemon ;;
232 (** log a list of libxslt's messages using a processing logger *)
233 let log_libxslt_msgs logger libxslt_logger =
236 | (LibXsltErrorMsg _) as msg -> logger#logBold (string_of_xslt_msg msg)
237 | (LibXsltDebugMsg _) as msg -> logger#logEmph (string_of_xslt_msg msg))
242 let veillogger = new Uwobo_common.libXsltLogger ;;
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
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 *)
258 ("http://127.0.0.1:" ^ string_of_int port ^ "/help")) ;
259 raise (Failure "Port already in use")
261 Unix.Unix_error (Unix.ECONNREFUSED, _, _) -> ()
263 match Unix.fork () with
265 Unix.handle_unix_error
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 ;
274 (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
275 0o664 = Unix.stdout) ;
276 Unix.close Unix.stderr ;
278 (Unix.openfile logfile [Unix.O_WRONLY ; Unix.O_APPEND ; Unix.O_CREAT]
279 0o664 = Unix.stderr) ;
280 prerr_endline "***** Starting a new session" ;
282 (* 3. We set up a new 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" ;
290 (* 4. We exec a new copy of uwobo *)
291 Unix.execve Sys.executable_name [||] environment
293 | child when child > 0 ->
294 (* let's check if the new UWOBO started correctly *)
296 (* It can raise Failure "Connection refused" *)
300 ("http://127.0.0.1:" ^ string_of_int port ^ "/help"))
301 with Unix.Unix_error (Unix.ECONNREFUSED, _, _) ->
302 raise (Failure "Connection refused"))
303 | _ -> failwith "Can't fork :-("
306 (* request handler action
307 @param syslogger Uwobo_logger.sysLogger instance used for logginf
308 @param styles Uwobo_styles.styles instance which keeps the stylesheets list
309 @param cmd_pipe output _channel_ used to _write_ update messages
310 @param res_pipe input _channel_ used to _read_ grandparent results
311 @param req http request instance
312 @param outchan output channel connected to http client
315 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
318 syslogger#log `Notice (sprintf "Connection from %s" req#clientAddr);
319 syslogger#log `Debug (sprintf "Received request: %s" req#path);
322 (let bindings = req#paramAll "bind" in
323 if bindings = [] then
324 return_error "No [key,stylesheet] binding provided" outchan
326 let cmd = sprintf "add %s" (String.concat ";" bindings) in
327 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
330 let logger = new Uwobo_logger.processingLogger () in
331 logger#log "Exiting" ;
332 respond_html logger#asHtml outchan ;
334 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
336 let logger = new Uwobo_logger.processingLogger () in
337 let port = int_of_string (req#param "port") in
338 let logfile = logfilename_of_port port in
340 start_new_session cmd_pipe res_pipe outchan port logfile ;
341 logger#log (sprintf "New session started: port = %d" port) ;
342 respond_html logger#asHtml outchan
344 Failure "int_of_string" ->
345 logger#log (sprintf "Invalid port number") ;
346 respond_html logger#asHtml outchan
347 | Failure "Port already in use" ->
348 Uwobo_common.return_error "port already in use" outchan
349 | Failure "Connection refused" ->
352 let ch = open_in logfile in
353 while true do log := (input_line ch ^ "\n") :: !log ; done
358 let rec get_last_lines acc =
360 (n,he::tl) when n > 0 ->
361 get_last_lines (he ^ "<br />" ^ acc) (n-1,tl)
364 (* we just show the last 10 lines of the log file *)
366 (if List.length !log > 0 then "<br />...<br />" else "<br />") ^
367 get_last_lines "" (10,!log)
369 Uwobo_common.return_error "daemon not initialized"
372 let cmd = sprintf "remove %s" (req#param "keys") in
373 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
375 let cmd = sprintf "reload %s" (req#param "keys") in
376 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
378 (let logger = new Uwobo_logger.processingLogger () in
379 (match styles#list with
380 | [] -> logger#log "No stylesheets loaded (yet)!"
382 logger#log "Stylesheets list:";
383 List.iter (fun s -> logger#log s) l);
384 respond_html logger#asHtml outchan)
386 let profile_list = Uwobo_profiles.list () in
387 respond_html ("<html><body><ul>" ^ String.concat "" (List.map (fun s -> "<li>" ^ s ^ "</li>") profile_list) ^ "</ul></body></html>") outchan
388 | "/createprofile" ->
389 let serialized_param_value_list = serialize_param_list req#params in
390 let cmd = sprintf "createprofile %s,%s,%s,%s,%s,%s,%s,%s"
391 (string_of_param_option req "id")
392 (string_of_param_option req "orig")
393 (string_of_param_option req "origpassword")
394 (string_of_param_option req "readperm")
395 (string_of_param_option req "writeperm")
396 (string_of_param_option req "adminperm")
397 (string_of_param_option req "password")
398 serialized_param_value_list
400 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
401 | "/removeprofile" ->
402 let cmd = sprintf "removeprofile %s,%s"
404 (string_of_param_option req "password")
406 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
408 let cmd = sprintf "setprofileparam %s,%s,%s,%s"
409 (string_of_param_option req "id")
410 (string_of_param_option req "password")
412 (string_of_param_option req "value")
414 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
416 let cmd = sprintf "setpassword %s,%s,%s"
418 (string_of_param_option req "oldpassword")
419 (string_of_param_option req "password")
421 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
422 | "/setpermission" ->
424 match req#param "for" with
427 | "admin" as forwhat ->
428 let cmd = sprintf "setpermission %s,%s,%s,%s"
430 (string_of_param_option req "password")
434 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
435 | _ -> Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) outchan
438 let pid = req#param "id" in
439 let password = try Some (req#param "password") with _ -> None in
440 let res = Uwobo_profiles.get_params pid ?password () in
442 ("<html><body><ul>" ^
443 String.concat "" (List.map (fun (k,v) -> "<li><key>" ^ k ^ "</key> = <value>" ^ v ^ "</value></li>") res) ^
444 "</ul></body></html>") outchan
446 let serialized_param_value_list = serialize_param_list req#params in
447 let cmd = sprintf "setparams %s,%s,%s"
449 (string_of_param_option req "password")
450 serialized_param_value_list
452 short_circuit_grandfather_and_client ~cmd ~cmd_pipe ~res_pipe outchan
454 let pid = req#param "id" in
455 let password = try Some (req#param "password") with _ -> None in
456 let key = req#param "key" in
457 let value = Uwobo_profiles.get_param pid ?password ~key () in
458 respond_html ("<html><body>" ^ value ^ "</body></html>") outchan
459 | "/getpermission" ->
460 let pid = req#param "id" in
461 let password = try Some (req#param "password") with _ -> None in
463 match req#param "for" with
465 | "write" -> Some `Write
466 | "admin" -> Some `Admin
472 let value = Uwobo_profiles.get_permission pid ?password forwhat in
473 respond_html ("<html><body>" ^ (if value then "public" else "private") ^ "</body></html>") outchan
474 | None -> Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) outchan ;
477 (* let logger = new Uwobo_logger.processingLogger () in *)
478 veillogger#clearMsgs;
479 let profile = try Some (req#param "profile") with _ -> None in
480 let password = try Some (req#param "password") with _ -> None in
481 let xmluri = req#param "xmluri" in
482 let keys = Pcre.split ~pat:"," (req#param "keys") in
483 (* notation: "local" parameters are those defined on a per-stylesheet
484 pasis (i.e. param.key.param=value), "global" parameters are those
485 defined for all stylesheets (i.e. param.param=value) *)
486 let (user_params, props) = parse_apply_params req#params in
490 | Some profile -> Uwobo_profiles.get_params profile ?password () in
492 (* user provided parameters override the profile parameters *)
493 let is_global_param x = Pcre.pmatch ~pat:"^(\\.[^.]+){1}$" ("." ^ x) in
494 let is_local_param x = Pcre.pmatch ~pat:"^(\\.[^.]+){2}$" ("." ^ x) in
495 let add key value params =
496 if List.mem_assoc key params then params else params @ [key,value]
499 (fun old_params (name, value) ->
501 | name when is_global_param name ->
502 (fun x -> add name value (old_params x))
503 | name when is_local_param name ->
504 let pieces = Pcre.extract ~pat:"^([^.]+)\\.(.*)" name in
505 let (key, name) = (pieces.(1), pieces.(2)) in
507 | x when x = key -> add name value (old_params x)
510 user_params profile_params
512 let (libxslt_errormode, libxslt_debugmode) =
513 parse_libxslt_msgs_mode req
515 syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
516 let domImpl = Gdome.domImplementation () in
517 let input = domImpl#createDocumentFromURI ~uri:xmluri () in
519 let tmp_xml, tmp_uri =
521 Filename.dirname (Helm_registry.get "uwobo.log_basename")
523 dir ^ "/input.xml", dir ^ "/input.uri"
525 ignore (domImpl#saveDocumentToFile ~doc:input ~name:tmp_xml ());
526 let oc = open_out tmp_uri in
527 output_string oc xmluri;
530 syslogger#log `Debug "Applying stylesheet chain ...";
532 let (write_result, media_type, encoding) = (* out_channel -> unit *)
534 ~logger:syslogger ~styles ~keys ~params ~props ~veillogger
535 ~errormode:libxslt_errormode ~debugmode:libxslt_debugmode
538 let content_type = (* value of Content-Type HTTP response header *)
539 sprintf "%s; charset=%s"
540 (match media_type with None -> get_media_type props | Some t -> t)
541 (match encoding with None -> get_encoding props | Some e -> e)
544 (sprintf "sending output to client (Content-Type: %s)...."
546 Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
547 Http_daemon.send_header "Content-Type" content_type outchan;
548 Http_daemon.send_CRLF outchan;
549 write_result outchan;
551 with Uwobo_failure errmsg ->
553 ("Stylesheet chain application failed: " ^ errmsg)
554 ~body: ("<h2>LibXSLT's messages:</h2>" ^
555 String.concat "<br />\n"
556 (List.map string_of_xslt_msg veillogger#msgs))
558 | "/help" -> respond_html usage_string outchan
560 Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) outchan);
561 syslogger#log `Debug (sprintf "%s done!" req#path);
563 | Http_types.Param_not_found attr_name ->
564 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
566 return_error ("Uncaught exception: " ^ (Printexc.to_string exc)) outchan
570 ~syslogger ~styles ~cmd_pipe ~res_pipe () (req: Http_types.request) outchan
573 (fun () -> try close_out outchan with Sys_error _ -> ())
574 (callback ~syslogger ~styles ~cmd_pipe ~res_pipe () req) outchan
576 (* UWOBO's startup *)
578 (* (1) system logger *)
580 debug_print (sprintf "Logging to file %s" logfile);
581 open_out_gen [Open_wronly; Open_append; Open_creat] logfile_perm logfile
584 new Uwobo_logger.sysLogger ~level:debug_level ~outchan:logger_outchan ()
587 (* (2) stylesheets list *)
588 let styles = new Uwobo_styles.styles in
589 (* (3) clean up actions *)
590 let last_process = ref true in
591 let http_child = ref None in
592 let die_nice () = (** at_exit callback *)
593 if !last_process then begin
594 (match !http_child with
596 | Some pid -> Unix.kill pid Sys.sigterm);
597 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name);
599 close_out logger_outchan
603 ignore (Sys.signal Sys.sigterm
604 (Sys.Signal_handle (fun _ -> raise Sys.Break)));
605 syslogger#log `Notice
606 (sprintf "%s started and listening on port %d" daemon_name port);
607 syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
608 Unix.putenv "http_proxy" ""; (* reset http_proxy to avoid libxslt problems *)
610 let (cmd_pipe_exit, cmd_pipe_entrance) = Unix.pipe () in
611 let (res_pipe_exit, res_pipe_entrance) = Unix.pipe () in
612 match Unix.fork () with
613 | child when child > 0 -> (* (4) parent: listen on cmd pipe for updates *)
614 http_child := Some child;
615 let stop_http_daemon () = (* kill child *)
616 debug_print (sprintf "UWOBOmaster: killing pid %d" child);
617 Unix.kill child Sys.sigterm; (* kill child ... *)
618 ignore (Unix.waitpid [] child); (* ... and its zombie *)
620 Unix.close cmd_pipe_entrance;
621 Unix.close res_pipe_exit;
622 let cmd_pipe = Unix.in_channel_of_descr cmd_pipe_exit in
623 let res_pipe = Unix.out_channel_of_descr res_pipe_entrance in
626 (* INVARIANT: 'Restart_HTTP_daemon' exception is raised only after
627 child process has been killed *)
628 debug_print "UWOBOmaster: waiting for commands ...";
629 let cmd = input_line cmd_pipe in
630 debug_print (sprintf "UWOBOmaster: received %s command" cmd);
631 (match cmd with (* command from grandchild *)
634 output_string res_pipe "UWOBOmaster: Hello, world!\n";
636 raise Restart_HTTP_daemon
637 | line when Pcre.pmatch ~rex:kill_cmd_RE line -> (* /kill *)
639 | line when Pcre.pmatch ~rex:add_cmd_RE line -> (* /add *)
641 Pcre.split ~pat:";" (Pcre.replace ~rex:add_cmd_RE line)
644 let logger = new Uwobo_logger.processingLogger () in
646 (fun binding -> (* add a <key, stylesheet> binding *)
647 let pieces = Pcre.split ~pat:"," binding in
650 logger#log (sprintf "adding binding <%s,%s>" key style);
651 veillogger#clearMsgs;
653 veillogger#clearMsgs;
654 styles#add key style;
655 log_libxslt_msgs logger veillogger;
657 logger#log (Printexc.to_string e))
658 | _ -> logger#log (sprintf "invalid binding %s" binding))
660 output_string res_pipe logger#asHtml;
662 raise Restart_HTTP_daemon
663 | line when Pcre.pmatch ~rex:remove_cmd_RE line -> (* /remove *)
665 let arg = Pcre.replace ~rex:remove_cmd_RE line in
666 let logger = new Uwobo_logger.processingLogger () in
667 veillogger#clearMsgs;
670 styles#remove (fun () -> styles#removeAll) styles#keys
672 log_libxslt_msgs logger veillogger;
673 output_string res_pipe (logger#asHtml);
674 raise Restart_HTTP_daemon
675 | line when Pcre.pmatch ~rex:reload_cmd_RE line -> (* /reload *)
677 let arg = Pcre.replace ~rex:reload_cmd_RE line in
678 let logger = new Uwobo_logger.processingLogger () in
679 veillogger#clearMsgs;
682 styles#reload (fun () -> styles#reloadAll) styles#keys
684 output_string res_pipe (logger#asHtml);
685 raise Restart_HTTP_daemon
686 | line when Pcre.pmatch ~rex:createprofile_cmd_RE line -> (* /createprofile *)
689 match (Pcre.split ~pat:"," (Pcre.replace ~rex:createprofile_cmd_RE line)) with
690 id::clone::clone_password::read_perm::write_perm::admin_perm::password::pv_list ->
691 let bool_option_of_string_option =
693 Some "true" -> Some true
694 | Some _ -> Some false
698 Uwobo_profiles.create
699 ?id:(string_option_of_string id)
700 ?clone:(string_option_of_string clone)
701 ?clone_password:(string_option_of_string clone_password)
702 ?read_perm:(bool_option_of_string_option (string_option_of_string read_perm))
703 ?write_perm:(bool_option_of_string_option (string_option_of_string write_perm))
704 ?admin_perm:(bool_option_of_string_option (string_option_of_string admin_perm))
705 ?password:(string_option_of_string password)
708 let pv_list' = (deserialize_param_list pv_list) in
711 Uwobo_profiles.set_param
712 pid ?password:(string_option_of_string password) ~key ~value ())
714 save_configuration () ;
715 output_string res_pipe ("Profile " ^ pid ^ " created. Hi " ^ pid) ;
716 raise Restart_HTTP_daemon
719 | line when Pcre.pmatch ~rex:removeprofile_cmd_RE line -> (* /removeprofile *)
722 match Pcre.split ~pat:"," (Pcre.replace ~rex:removeprofile_cmd_RE line) with
723 [pid; password] -> pid, (string_option_of_string password)
726 Uwobo_profiles.remove pid ?password () ;
727 save_configuration () ;
728 output_string res_pipe "Done" ;
729 raise Restart_HTTP_daemon
730 | line when Pcre.pmatch ~rex:setparams_cmd_RE line -> (* /setparams *)
731 stop_http_daemon () ;
732 let pid, password, pv_list =
733 match Pcre.split ~pat:"," (Pcre.replace ~rex:setparams_cmd_RE line) with
734 pid::password::pv_list ->
735 pid, (string_option_of_string password), (deserialize_param_list pv_list)
739 (fun (key, value) -> Uwobo_profiles.set_param pid ?password ~key ~value ())
741 save_configuration () ;
742 output_string res_pipe "Done" ;
743 raise Restart_HTTP_daemon
744 | line when Pcre.pmatch ~rex:setprofileparam_cmd_RE line -> (* /setprofileparam *)
746 let pid, password, key, value =
747 match Pcre.split ~pat:"," (Pcre.replace ~rex:setprofileparam_cmd_RE line) with
748 [pid; password; key; value] ->
749 pid, (string_option_of_string password), key, (string_option_of_string value)
752 Uwobo_profiles.set_param pid ?password ~key ~value () ;
753 save_configuration () ;
754 output_string res_pipe "Done" ;
755 raise Restart_HTTP_daemon
756 | line when Pcre.pmatch ~rex:setpassword_cmd_RE line -> (* /setpassword *)
758 let pid, old_password, password =
759 match Pcre.split ~pat:"," (Pcre.replace ~rex:setpassword_cmd_RE line) with
760 [pid; old_password; password] ->
761 pid, (string_option_of_string old_password), (string_option_of_string password)
764 Uwobo_profiles.set_password pid ?old_password password ;
765 save_configuration () ;
766 output_string res_pipe "Done" ;
767 raise Restart_HTTP_daemon
768 | line when Pcre.pmatch ~rex:setpermission_cmd_RE line -> (* /setpermission *)
770 let permission_of_string =
776 and bool_of_string s = "public" = s
778 let pid, password, forwhat, value =
779 match Pcre.split ~pat:"," (Pcre.replace ~rex:setpermission_cmd_RE line) with
780 [pid; password; forwhat; value] ->
781 pid, (string_option_of_string password), (permission_of_string forwhat), (bool_of_string value)
784 Uwobo_profiles.set_permission pid ?password forwhat value ;
785 save_configuration () ;
786 output_string res_pipe "Done" ;
787 raise Restart_HTTP_daemon
788 | cmd -> (* invalid interprocess command received *)
789 syslogger#log `Warning
790 (sprintf "Ignoring invalid interprocess command: '%s'" cmd))
793 | Restart_HTTP_daemon ->
794 close_in cmd_pipe; (* these calls close also fds *)
796 | Sys.Break as exn -> raise exn
797 | e -> (* Should we return a 404 error here? Maybe... (how?) *)
798 output_string res_pipe (Printexc.to_string e);
799 close_in cmd_pipe; (* these calls close also fds *)
801 | 0 -> (* (5) child: serve http requests *)
802 Unix.close cmd_pipe_exit;
803 Unix.close res_pipe_entrance;
804 last_process := false;
805 let cmd_pipe = Unix.out_channel_of_descr cmd_pipe_entrance in
806 let res_pipe = Unix.in_channel_of_descr res_pipe_exit in
807 debug_print (sprintf "Starting HTTP daemon on port %d ..." port);
808 (* next invocation doesn't return, process will keep on serving HTTP
809 requests until it will get killed by father *)
810 let d_spec = Http_daemon.daemon_spec
812 ~callback:(callback ~syslogger ~styles ~cmd_pipe ~res_pipe ()) ()
814 Http_daemon.main d_spec
815 | _ (* < 0 *) -> (* fork failed :-((( *)
816 failwith "Can't fork :-("
820 (* daemon initialization *)
822 Sys.catch_break true;
824 with Sys.Break -> () (* 'die_nice' registered with at_exit *)