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