Fixed a subtle race. Thanks to Kyoungsoo.
[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 let direct_fifo_table: (string,(string*string*string*Unix.file_descr) option) Hashtbl.t = Hashtbl.create 1024
25 let pidmap: (int,string*Unix.file_descr) Hashtbl.t = Hashtbl.create 1024
26
27 let rec list_check lst elt =
28   match lst with
29     | [] -> false
30     | car::cdr -> if (car==elt) then true else list_check cdr elt
31
32 let openentry_int fifoin =
33   let fdin =
34     try openfile fifoin [O_RDONLY;O_NONBLOCK] 0o777 with 
35         e->fprintf logfd "Error opening and connecting FIFO: %s,%o\n" fifoin 0o777;flush logfd;raise e
36   in
37     fdin
38
39
40 (** Open fifos for a session. SHOULD NOt shutdown vsys if the fifos don't exist *)
41 let openentry_in root_dir fqp_in backend_spec =
42     Dirwatcher.mask_watch root_dir;
43   let fd_in = openentry_int fqp_in in
44     Dirwatcher.unmask_watch root_dir [S_Open];
45   let (fqp,slice_name) = backend_spec in
46     Hashtbl.replace direct_fifo_table fqp_in (Some(root_dir,fqp,slice_name,fd_in))
47
48 let openentry root_dir fqp backend_spec =
49   let fqp_in = String.concat "." [fqp;"in"] in
50     openentry_in root_dir fqp_in backend_spec
51
52 let reopenentry fifoin =
53   let entry = try Hashtbl.find direct_fifo_table fifoin with _ -> None in
54     match entry with
55       | Some(dir, fqp,slice_name,fd) -> close_if_open fd;openentry_in dir fifoin (fqp,slice_name)
56       | None -> ()
57
58 (* vsys is activated when a client opens an in file *)
59 let connect_file fqp_in =
60   (* Do we care about this file? *)
61   let entry_info = try
62     Hashtbl.find direct_fifo_table fqp_in with _ -> None in
63     match entry_info with
64       | Some(_,execpath,slice_name,fifo_fdin) ->
65           fprintf logfd "Executing %s for slice %s\n" execpath slice_name;flush logfd;
66           begin
67             let len = String.length fqp_in in
68             let fqp = String.sub fqp_in 0 (len-3) in
69             let fqp_out = String.concat "." [fqp;"out"] in
70             let fifo_fdout =
71               try openfile fqp_out [O_WRONLY;O_NONBLOCK] 0o777 with
72                   _->fprintf logfd "%s Output pipe not open, using stdout in place of %s\n" slice_name fqp_out;flush logfd;stdout
73             in
74             ignore(sigprocmask SIG_BLOCK [Sys.sigchld]);
75             (
76             clear_nonblock fifo_fdin;
77             let pid=try Some(create_process execpath [|execpath;slice_name|] fifo_fdin fifo_fdout fifo_fdout) with e -> None in
78               match pid with 
79                 | Some(pid) ->Hashtbl.add pidmap pid (fqp_in,fifo_fdout)
80                 | None ->fprintf logfd "Error executing service: %s\n" execpath;flush logfd;reopenentry fqp_in
81             );
82             ignore(sigprocmask SIG_UNBLOCK [Sys.sigchld]);
83           end
84       | None -> ()
85
86
87 (** Make a pair of fifo entries *)
88 let mkentry fqp abspath perm uname = 
89   fprintf logfd "Making entry %s->%s\n" fqp abspath;flush logfd;
90   let fifoin=sprintf "%s.in" fqp in
91   let fifoout=sprintf "%s.out" fqp in
92     (try Unix.unlink fifoin with _ -> ());
93     (try Unix.unlink fifoout with _ -> ());
94     (try 
95        let infname =(sprintf "%s.in" fqp) in
96        let outfname =(sprintf "%s.out" fqp) in
97          Unix.mkfifo infname 0o666;
98          Unix.mkfifo outfname 0o666;
99          ( (* Make the user the owner of the pipes in a non-chroot environment *)
100            if (!Globals.nochroot) then
101              let pwentry = Unix.getpwnam uname in
102                Unix.chown infname pwentry.pw_uid pwentry.pw_gid; 
103                Unix.chown outfname pwentry.pw_uid pwentry.pw_gid
104          );
105          Success
106      with 
107          e->fprintf logfd "Error creating FIFO: %s->%s. May be something wrong at the frontend.\n" fqp fifoout;flush logfd;Failed)
108
109
110 (** Close fifos that just got removed *)
111 let closeentry fqp =
112   let fqp_in = String.concat "." [fqp;"in"] in
113   let entry = try Hashtbl.find direct_fifo_table fqp_in with Not_found -> None in
114     match entry with
115       | None -> ()
116       | Some(_,_,_,fd) -> 
117           close_if_open fd;
118           Hashtbl.remove direct_fifo_table fqp_in
119
120 let sigchld_handle s =
121   let pid,_=Unix.waitpid [Unix.WNOHANG] 0 in
122     try
123       let fqp_in,fd_out = Hashtbl.find pidmap pid in
124         begin
125         reopenentry fqp_in;
126         if (fd_out <> stdout) then close_if_open fd_out
127         end
128
129     with _ -> ()
130
131 let rec add_dir_watch fqp =
132   Dirwatcher.add_watch fqp [S_Open] direct_fifo_handler
133 and
134 direct_fifo_handler wd dirname evlist fname =
135   let is_event = list_check evlist in
136     if (is_event Open) then 
137       let fqp_in = String.concat "/" [dirname;fname] in
138       begin
139         connect_file fqp_in;
140         add_dir_watch dirname
141       end
142
143 let del_dir_watch fqp =
144   (* XXX Dirwatcher.del_watch fqp *)
145   ()
146
147 let initialize () =
148       Sys.set_signal Sys.sigchld (Sys.Signal_handle sigchld_handle)