outer_cgi 0.2.3

A barebones CGI/FCGI wrapper.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use libc;
use nix::errno::Errno;
use nix::fcntl::FcntlArg;
use nix::sys::stat::SFlag;
use nix;
use std::collections::HashMap;
use std::ffi::CString;
use std::fs::File;
use std::io;
use std::io::{BufRead,BufReader};
use std::net::{TcpStream, TcpListener};
use std::os::unix::io::{RawFd,FromRawFd,IntoRawFd,AsRawFd};
use std::os::unix::net::UnixListener;
use std::path::{Path,PathBuf};
use std::slice::Iter;
use std;
use super::{Listener, ParanoidTcpListener, OptionHandler, OptionParseOutcome};

fn fd_ok(fd: RawFd) -> bool {
    match nix::fcntl::fcntl(fd, FcntlArg::F_GETFD) {
        // The file descriptor is open and valid.
        Ok(_) => true,
        // The file descriptor is not open.
        Err(nix::Error::Sys(Errno::EBADF)) => false,
        // The fcntl call failed for some other reason. Panic, for all the good
        // that'll do.
        Err(e) => panic!("error calling fcntl({}): {}", fd, e),
    }
}

fn fd_is_sock(fd: RawFd) -> bool {
    let st = nix::sys::stat::fstat(fd)
        .expect("Unexpected error calling fstat");
    (SFlag::from_bits_truncate(st.st_mode) & SFlag::S_IFMT) == SFlag::S_IFSOCK 
}

fn stderr_to_syslog(identifier: Option<String>) {
    // let's make a pipe
    let (read_fd, write_fd) = nix::unistd::pipe()
        .expect("Unexpected error making syslog diversion pipe");
    assert_ne!(read_fd, 2);
    if write_fd != 2 {
        nix::unistd::dup2(write_fd, 2)
            .expect("Unexpected error calling dup2 on syslog diversion pipe");
        let _ = nix::unistd::close(write_fd); // ignore error
    }
    let read = unsafe { File::from_raw_fd(read_fd) };
    // identifier needs to hang around as long as we keep calling syslog, or
    // bad things will happen! therefore, we will move it into the closure
    let identifier = identifier.unwrap_or_else(|| {
        std::env::args().next()
            .map(|x| {
                match x.rfind('/') {
                    Some(i) => x[i+1..].to_owned(),
                    None => x,
                }
            }).unwrap_or_else(|| "outer_cgi_app".to_string())
    });
    let identifier = CString::new(identifier).unwrap();
    use nix::unistd::ForkResult;
    match unsafe{nix::unistd::fork()} {
        Ok(ForkResult::Child) => {
            let _ = nix::unistd::close(write_fd); // ignore result
            unsafe {
                libc::openlog(identifier.as_ptr(), 0, libc::LOG_USER);
            }
            let mut read = BufReader::new(read);
            let mut buf = Vec::new();
            while let Ok(count) = read.read_until(b'\n', &mut buf) {
                if count == 0 { break }
                buf.push(0);
                unsafe {
                    libc::syslog(libc::LOG_WARNING,
                                 b"%s\0".as_ptr() as *const libc::c_char,
                                 buf.as_ptr() as *const libc::c_char);
                }
                buf.clear();
            }
            std::process::exit(0)
        },
        Ok(ForkResult::Parent{..}) => {
            let _ = nix::unistd::close(read_fd); // ignore result
        },
        Err(_) => {
            // panic, for all the good it'll do
            panic!("forking for syslog diversion failed!");
        }
    }
}

/// If we are being run in strict compliance with the FCGI specification
/// file descriptor 0 (normally stdin) is an FCGI listen socket, and file
/// descriptors 1 and 2 (stdout/stderr) are closed. In addition, even if those
/// FDs are valid, if FD 0 is a socket then stderr might not go to a place that
/// makes any sense.
///
/// This function:
/// - Ensures that FDs 0, 1, and 2 are valid, to avoid problems down the line.
/// - Detects whether FD 0 is a listen socket, and returns a Listener for it if
/// so.
/// - If FD 2 was invalid **IOR** FD 0 was a listen socket, redirects stderr
/// to syslog, with an automatically generated identifier.
pub fn fix_fds(env: &HashMap<String,String>) -> Option<Box<dyn Listener>> {
    // let's ensure that all standard file descriptors are valid
    let fd0_ok = fd_ok(0);
    let fd1_ok = fd_ok(1);
    let fd2_ok = fd_ok(2);
    if !fd0_ok || !fd1_ok || !fd2_ok {
        // at least one of the standard FDs is not open.
        let devnull = nix::fcntl::open("/dev/null", nix::fcntl::OFlag::O_RDWR,
                                       nix::sys::stat::Mode::empty())
            .expect("Error opening /dev/null");
        if !fd0_ok && devnull != 0 { nix::unistd::dup2(devnull, 0).unwrap(); }
        if !fd1_ok && devnull != 1 { nix::unistd::dup2(devnull, 1).unwrap(); }
        // (yes, we're just going to close fd 2 in a moment anyway, but this
        // way we ensure pipe() doesn't return file descriptor 2 as the read
        // end of the stderr pipe)
        if !fd2_ok && devnull != 2 { nix::unistd::dup2(devnull, 2).unwrap(); }
        if devnull > 2 { nix::unistd::close(devnull).unwrap(); }
    }
    // if FD 2 doesn't go anywhere OR FD 0 is a listen socket
    let have_sock = fd_is_sock(0);
    if !fd2_ok || have_sock {
        stderr_to_syslog(None)
    }
    if fd0_ok && have_sock {
        if let Some(list) = env.get("FCGI_WEB_SERVER_ADDRS") {
            let result = nix::sys::socket::getsockname(0);
            use nix::sys::socket::SockAddr;
            match result {
                Ok(SockAddr::Inet(_)) => {
                    Some(Box::new(unsafe{
                        ParanoidTcpListener::with(TcpListener::from_raw_fd(0),
                                                  list).unwrap()
                    }))
                },
                _ => {
                    eprintln!("WARNING: Value of FCGI_WEB_SERVER_ADDRS is \
                               ignored for non-TCP sockets!");
                    Some(Box::new(unsafe{TcpListener::from_raw_fd(0)}))
                },
            }
        }
        else {
            // A bare listener will do
            Some(Box::new(unsafe{TcpListener::from_raw_fd(0)}))
        }
    }
    else {
        None
    }
}

pub struct UnixSocketOptions {
    chown: Option<nix::unistd::Uid>,
    chgrp: Option<nix::unistd::Gid>,
    chmod: Option<nix::sys::stat::Mode>,
}
impl UnixSocketOptions {
    pub fn new() -> UnixSocketOptions {
        UnixSocketOptions {
            chown: None,
            chgrp: None,
            chmod: None,
        }
    }
}
impl OptionHandler for UnixSocketOptions {
    fn maybe_parse_option<'a>(&mut self, arg: &str, it: &mut Iter<String>)
                              -> OptionParseOutcome {
        match arg {
            "--chmod" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --chmod");
                        return OptionParseOutcome::Failed
                    },
                };
                match u32::from_str_radix(arg, 8) {
                    Err(_) => {
                        eprintln!("Invalid argument for --chmod");
                        return OptionParseOutcome::Failed
                    },
                    Ok(mode) if mode > 0o777 => {
                        eprintln!("Invalid argument for --chmod");
                        return OptionParseOutcome::Failed
                    },
                    Ok(mode) => {
                        self.chmod = Some(nix::sys::stat::Mode::from_bits_truncate(mode));
                        OptionParseOutcome::Consumed
                    }
                }
            },
            "--chown" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --chown");
                        return OptionParseOutcome::Failed
                    },
                };
                match libc::uid_t::from_str_radix(arg, 10) {
                    Err(_) => {
                        eprintln!("Invalid argument for --chown");
                        return OptionParseOutcome::Failed
                    },
                    Ok(mode) => {
                        self.chown = Some(nix::unistd::Uid::from_raw(mode));
                        OptionParseOutcome::Consumed
                    }
                }
            },
            "--chgrp" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --chgrp");
                        return OptionParseOutcome::Failed
                    },
                };
                match libc::gid_t::from_str_radix(arg, 10) {
                    Err(_) => {
                        eprintln!("Invalid argument for --chgrp");
                        return OptionParseOutcome::Failed
                    },
                    Ok(mode) => {
                        self.chgrp = Some(nix::unistd::Gid::from_raw(mode));
                        OptionParseOutcome::Consumed
                    }
                }
            },
            _ => OptionParseOutcome::Ignored,
        }
    }
}

impl Listener for UnixListener {
    fn accept_connection(&mut self) -> io::Result<TcpStream> {
        match self.accept() {
            Ok((sock, _)) => Ok(unsafe{TcpStream::from_raw_fd(sock.into_raw_fd())}),
            Err(e) => Err(e),
        }
    }
}

pub fn listen(path: &Path, options: UnixSocketOptions)
              -> io::Result<UnixListener> {
    // This will cause the socket to be created with the desired permissions.
    let old_umask = unsafe{libc::umask(options.chmod.map(|x| x.bits()).unwrap_or(0o660)^0o777)};
    let ret = UnixListener::bind(path)?;
    // restore the old umask
    unsafe{libc::umask(old_umask)};
    if options.chown.is_some() || options.chgrp.is_some() {
        match nix::unistd::chown(path, options.chown, options.chgrp) {
            Ok(_) => (),
            Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
        }
        // now, consume any connections that might have been made while the
        // owner/group were wrong
        // (this should not error; I think panicking on a near-impossible
        // situation that would break code downstream is better than
        // either copy-pasting the same error conversion shim twice more or
        // just ignoring the result)
        nix::fcntl::fcntl(ret.as_raw_fd(),
                          FcntlArg::F_SETFL(nix::fcntl::OFlag::O_NONBLOCK))
            .unwrap();
        while let Ok(_) = ret.accept() {}
        nix::fcntl::fcntl(ret.as_raw_fd(),
                          FcntlArg::F_SETFL(nix::fcntl::OFlag::empty()))
            .unwrap();
    }
    Ok(ret)
}

pub struct UnixOSOptions {
    setuid: Option<nix::unistd::Uid>,
    setgid: Option<nix::unistd::Gid>,
    chroot: Option<PathBuf>,
    syslog: Option<String>,
    daemonize: bool,
}
impl UnixOSOptions {
    pub fn new() -> UnixOSOptions {
        UnixOSOptions {
            setuid: None,
            setgid: None,
            chroot: None,
            syslog: None,
            daemonize: false,
        }
    }
    fn nix_post_setup(self) -> nix::Result<()> {
        if let Some(path) = &self.chroot {
            nix::unistd::chroot(path)?;
        }
        if let Some(gid) = self.setgid {
            nix::unistd::setgid(gid)?;
        }
        if let Some(uid) = self.setuid {
            nix::unistd::setuid(uid)?;
        }
        if let Some(identifier) = self.syslog {
            stderr_to_syslog(Some(identifier));
        }
        if self.daemonize {
            // use the old double-fork trick
            // use libc::_exit instead of std::process::exit because we don't
            // *want* to clean anything up
            use nix::unistd::ForkResult;
            match unsafe{nix::unistd::fork()}? {
                ForkResult::Child =>
                    match unsafe{nix::unistd::fork()}? {
                        ForkResult::Child => (),
                        _ => unsafe { libc::_exit(0) },
                    },
                _ => unsafe { libc::_exit(0) },
            }
            let devnull = nix::fcntl::open("/dev/null",
                                           nix::fcntl::OFlag::O_RDWR,
                                           nix::sys::stat::Mode::empty())
                .unwrap();
            if devnull != 0 { nix::unistd::dup2(devnull, 0).unwrap(); }
            if devnull != 1 { nix::unistd::dup2(devnull, 1).unwrap(); }
            if devnull >= 2 { nix::unistd::close(devnull).unwrap(); }
        }
        Ok(())
    }
    pub fn post_setup(self) -> io::Result<()> {
        self.nix_post_setup().map_err(|x|
                                      io::Error::new(io::ErrorKind::Other,x))
    }
}
impl OptionHandler for UnixOSOptions {
    fn maybe_parse_option<'a>(&mut self, arg: &str, it: &mut Iter<String>)
                              -> OptionParseOutcome {
        match arg {
            "--setuid" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --setuid");
                        return OptionParseOutcome::Failed
                    },
                };
                match libc::uid_t::from_str_radix(arg, 10) {
                    Err(_) => {
                        eprintln!("Invalid argument for --setuid");
                        return OptionParseOutcome::Failed
                    },
                    Ok(mode) => {
                        self.setuid = Some(nix::unistd::Uid::from_raw(mode));
                        OptionParseOutcome::Consumed
                    }
                }
            },
            "--setgid" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --setgid");
                        return OptionParseOutcome::Failed
                    },
                };
                match libc::gid_t::from_str_radix(arg, 10) {
                    Err(_) => {
                        eprintln!("Invalid argument for --setgid");
                        return OptionParseOutcome::Failed
                    },
                    Ok(mode) => {
                        self.setgid = Some(nix::unistd::Gid::from_raw(mode));
                        OptionParseOutcome::Consumed
                    }
                }
            },
            "--chroot" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --chroot");
                        return OptionParseOutcome::Failed
                    },
                };
                self.chroot = Some(PathBuf::from(arg));
                OptionParseOutcome::Consumed
            },
            "--syslog" => {
                let arg = match it.next() {
                    Some(arg) => arg,
                    None => {
                        eprintln!("Missing argument for --syslog");
                        return OptionParseOutcome::Failed
                    },
                };
                self.syslog = Some(arg.to_owned());
                OptionParseOutcome::Consumed
            },
            "--daemonize" => {
                self.daemonize = true;
                OptionParseOutcome::Consumed
            },
            _ => OptionParseOutcome::Ignored,
        }
    }
}