2e1e60a0b372b63996f76198a8c94bdf194ef460
[vsys.git] / directfifowatcher.ml
1 (** directfifowatcher.ml: Routines to handle non-persistent scripts *)
2 (* Semantics:
3  *      - The 'out' descriptor must be opened first
4  *      - As soon as the backend script dies, the connection to the entry is
5  *      closed.
6  *      - To avoid user-inflicted pain, all entries are opened at the time
7  *      that they are created. Reopening these entries is a little complicated
8  *      but nevertheless sound:
9  *              * When a script dies, its fd is reopened
10  *              * If a script fails to execute, its fd is closed and reopened to
11  *              beat a race that can happen when the user closes the connection
12  *              before the script can be launched.
13  *)
14
15 open Inotify
16 open Unix
17 open Globals
18 open Dirwatcher
19 open Printf
20 open Splice
21
22 let close_if_open fd = (try (ignore(close fd);) with _ -> ())
23
24 type in_pathname = string
25 type directory = string
26 type base_pathname = string
27 type slice_name = string
28
29
30 let direct_fifo_table: (in_pathname,(directory*base_pathname*slice_name*Unix.file_descr) option) Hashtbl.t = 
31   Hashtbl.create 1024
32
33 let pidmap: (int,in_pathname * Unix.file_descr) Hashtbl.t = Hashtbl.create 1024
34
35 let rec list_check lst elt =
36   match lst with
37     | [] -> false
38     | car::cdr -> if (car==elt) then true else list_check cdr elt
39
40 let openentry_int fifoin =
41   let fdin =
42     try openfile fifoin [O_RDONLY;O_NONBLOCK] 0o777 with 
43         e->logprint "Error opening and connecting FIFO: %s,%o\n" fifoin 0o777;raise e
44   in
45     fdin
46
47 (** Open entry safely, by first masking out the file to be opened *)
48 let openentry_safe root_dir fqp_in backend_spec =
49   Dirwatcher.mask_watch fqp_in;
50   let fd_in = openentry_int fqp_in in
51     let (fqp,slice_name) = backend_spec in
52       Hashtbl.replace direct_fifo_table fqp_in (Some(root_dir,fqp,slice_name,fd_in))
53
54 let openentry root_dir fqp backend_spec =
55   let fqp_in = String.concat "." [fqp;"in"] in
56     openentry_safe root_dir fqp_in backend_spec
57
58 let reopenentry fifoin =
59   let entry = try Hashtbl.find direct_fifo_table fifoin with _ -> None in
60     match entry with
61       | Some(dir, fqp,slice_name,fd) -> close_if_open fd;openentry_safe dir fifoin (fqp,slice_name)
62       | None -> ()
63
64 (* vsys is activated when a client opens an in file *)
65 let connect_file fqp_in =
66   (* Do we care about this file? *)
67   let entry_info = try
68     Hashtbl.find direct_fifo_table fqp_in with _ -> None in
69     match entry_info with
70       | Some(_,execpath,slice_name,fifo_fdin) ->
71           (*fprintf logfd "Executing %s for slice %s\n" execpath
72            * slice_name;flush logfd;*)
73           begin
74             let len = String.length fqp_in in
75             let fqp = String.sub fqp_in 0 (len-3) in
76             let fqp_out = String.concat "." [fqp;"out"] in
77             let fifo_fdout =
78               try openfile fqp_out [O_WRONLY;O_NONBLOCK] 0o777 with
79                   _->logprint "%s Output pipe not open, using stdout in place of %s\n" slice_name fqp_out;stdout
80             in
81               ignore(sigprocmask SIG_BLOCK [Sys.sigchld]);
82               (
83                 clear_nonblock fifo_fdin;
84                 let pid=try Some(create_process execpath [|execpath;slice_name|] fifo_fdin fifo_fdout fifo_fdout) with e -> None in
85                   match pid with 
86                     | Some(pid) ->
87                         if (fifo_fdout <> stdout) then close_if_open fifo_fdout;
88                         Hashtbl.add pidmap pid (fqp_in,fifo_fdout)
89                     | None ->logprint "Error executing service: %s\n" execpath;reopenentry fqp_in
90               );
91               ignore(sigprocmask SIG_UNBLOCK [Sys.sigchld]);
92           end
93       | None -> ()
94
95
96 (** Make a pair of fifo entries *)
97 let mkentry fqp abspath perm uname = 
98   logprint "Making entry %s->%s\n" fqp abspath;
99   let fifoin=sprintf "%s.in" fqp in
100   let fifoout=sprintf "%s.out" fqp in
101     (try Unix.unlink fifoin with _ -> ());
102     (try Unix.unlink fifoout with _ -> ());
103     (try 
104        let infname =(sprintf "%s.in" fqp) in
105        let outfname =(sprintf "%s.out" fqp) in
106          Unix.mkfifo infname 0o666;
107          Unix.mkfifo outfname 0o666;
108          ( (* Make the user the owner of the pipes in a non-chroot environment *)
109            if (!Globals.nochroot) then
110              let pwentry = Unix.getpwnam uname in
111                Unix.chown infname pwentry.pw_uid pwentry.pw_gid; 
112                Unix.chown outfname pwentry.pw_uid pwentry.pw_gid
113          );
114          Success
115      with 
116          e->logprint "Error creating FIFO: %s->%s. May be something wrong at the frontend.\n" fqp fifoout;Failed)
117
118
119 (** Close fifos that just got removed *)
120 let closeentry fqp =
121   let fqp_in = String.concat "." [fqp;"in"] in
122   let entry = try Hashtbl.find direct_fifo_table fqp_in with Not_found -> None in
123     match entry with
124       | None -> ()
125       | Some(_,_,_,fd) -> 
126           close_if_open fd;
127           Hashtbl.remove direct_fifo_table fqp_in
128
129 let sigchld_handle s =
130   let pid,_=Unix.waitpid [Unix.WNOHANG] 0 in
131     try
132       let fqp_in,fd_out = Hashtbl.find pidmap pid in
133         begin
134           reopenentry fqp_in
135         end
136
137     with _ -> ()
138
139 let rec add_dir_watch fqp =
140   Dirwatcher.add_watch fqp [S_Open] direct_fifo_handler
141 and
142     direct_fifo_handler wd dirname evlist fname =
143   let is_event = list_check evlist in
144     if (is_event Open) then 
145       let fqp_in = String.concat "/" [dirname;fname] in
146           connect_file fqp_in
147
148 let del_dir_watch fqp =
149   ()
150
151 let initialize () =
152   Sys.set_signal Sys.sigchld (Sys.Signal_handle sigchld_handle)