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