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
use crate::Toolbox;
#[cfg(feature="readline")]
use crate::completer::CmdCompleter;
#[cfg(feature="network")]
use crate::crypto::OwnedTlsStream;
#[cfg(feature="readline")]
use rustyline::{self, Editor};

use std::fs::File;
use std::sync::{Arc, Mutex};
use bufstream::BufStream;
use std::io;
use std::io::prelude::*;
use std::fmt::Debug;
#[cfg(all(unix, feature="network"))]
use std::os::unix::net::UnixStream;
#[cfg(unix)]
use std::os::unix::io::{RawFd, AsRawFd};


#[derive(Debug)]
pub enum PromptError {
    Io(io::Error),
    Eof,
    #[cfg(feature="readline")]
    Other(rustyline::error::ReadlineError),
}

#[cfg(feature="readline")]
impl From<rustyline::error::ReadlineError> for PromptError {
    fn from(err: rustyline::error::ReadlineError) -> PromptError {
        use rustyline::error::ReadlineError;
        match err {
            ReadlineError::Io(err) => PromptError::Io(err),
            ReadlineError::Eof => PromptError::Eof,
            x => PromptError::Other(x),
        }
    }
}

impl From<io::Error> for PromptError {
    fn from(err: io::Error) -> PromptError {
        PromptError::Io(err)
    }
}


/// Wraps a Read object and a Write object into a Read/Write object.
#[derive(Debug)]
pub struct RW<R: Read, W: Write>(R, W);

#[cfg(unix)]
impl<R: Read+AsRawFd, W: Write+AsRawFd> RW<R, W> {
    #[inline]
    pub fn as_raw_fd(&self) -> (RawFd, RawFd) {
        let r = self.0.as_raw_fd();
        let w = self.1.as_raw_fd();
        (r, w)
    }
}

impl<R: Read, W: Write> Read for RW<R, W> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<R: Read, W: Write> Write for RW<R, W> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.1.write(buf)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        self.1.flush()
    }
}


pub trait R: Read + Debug {}
impl<T> R for T where T: Read + Debug {}

pub trait W: Write + Debug {}
impl<T> W for T where T: Write + Debug {}


/// The interface that the [`Shell`] uses.
///
/// [`Shell`]: ../shell/struct.Shell.html
#[derive(Debug)]
pub enum Interface {
    #[cfg(feature="readline")]
    Fancy((io::Stdin, io::Stdout, Editor<CmdCompleter>)),
    Stdio(BufStream<RW<io::Stdin, io::Stdout>>),
    File(BufStream<RW<File, File>>),
    RWPair(BufStream<RW<Box<R>, Box<W>>>),
    #[cfg(feature="network")]
    Tls(Box<BufStream<OwnedTlsStream>>),
    #[cfg(all(unix, feature="network"))]
    Ipc(BufStream<UnixStream>),
    Dummy(Vec<u8>),
}

impl Interface {
    #[allow(unused_variables)]
    pub fn default(toolbox: &Arc<Mutex<Toolbox>>) -> Interface {
        #[cfg(feature="readline")]
        let ui = Interface::fancy(toolbox.clone());
        #[cfg(not(feature="readline"))]
        let ui = Interface::stdio();

        ui
    }

    #[cfg(feature="readline")]
    pub fn fancy(toolbox: Arc<Mutex<Toolbox>>) -> Interface {
        let mut rl = Editor::new();
        let c = CmdCompleter::new(toolbox);
        rl.set_helper(Some(c));

        Interface::Fancy((io::stdin(), io::stdout(), rl))
    }

    pub fn stdio() -> Interface {
        Interface::Stdio(BufStream::new(RW(io::stdin(), io::stdout())))
    }

    // TODO: this can fail
    pub fn file(input: Option<File>, output: Option<File>) -> Interface {
        let input = input.unwrap_or_else(|| File::open("/dev/null").unwrap());
        let output = output.unwrap_or_else(|| File::open("/dev/null").unwrap());

        Interface::File(BufStream::new(RW(input, output)))
    }

    pub fn rw_pair(input: Box<R>, output: Box<W>) -> Interface {
        Interface::RWPair(BufStream::new(RW(input, output)))
    }

    pub fn dummy() -> Interface {
        Interface::Dummy(Vec::new())
    }

    pub fn readline_raw<RW: BufRead + Write>(prompt: &str, x: &mut RW) -> Result<String, PromptError> {
        x.write_all(prompt.as_bytes())?;
        x.flush()?;

        let mut buf = String::new();
        x.read_line(&mut buf)?;

        if buf.is_empty() {
            return Err(PromptError::Eof)
        }

        let buf = buf.trim_end().to_owned();

        Ok(buf)
    }

    pub fn readline(&mut self, prompt: &str) -> Result<String, PromptError> {
        match *self {
            #[cfg(feature="readline")]
            Interface::Fancy(ref mut x) => {
                let buf = x.2.readline(prompt)?;
                Ok(buf)
            },
            Interface::Stdio(ref mut x) => Self::readline_raw(prompt, x),
            Interface::File(ref mut x) => Self::readline_raw(prompt, x),
            Interface::RWPair(ref mut x) => Self::readline_raw(prompt, x),
            #[cfg(feature="network")]
            Interface::Tls(ref mut x) => Self::readline_raw(prompt, x),
            #[cfg(all(unix, feature="network"))]
            Interface::Ipc(ref mut x) => Self::readline_raw(prompt, x),
            Interface::Dummy(ref mut _x) => unimplemented!(),
        }
    }

    #[cfg(feature="readline")]
    pub fn add_history_entry(&mut self, line: &str) {
        if let Interface::Fancy(ref mut x) = *self {
            x.2.add_history_entry(line);
        }
    }

    #[cfg(unix)]
    #[inline]
    pub fn pipe(&mut self) -> Option<(RawFd, RawFd, RawFd)> {
        match *self {
            // this connects the real stdio automatically
            #[cfg(feature="readline")]
            Interface::Fancy(_) => None,
            Interface::Stdio(ref ui) => {
                let (r, w) = ui.get_ref().as_raw_fd();
                Some((r, w, w))
            },
            Interface::File(ref ui) => {
                let (r, w) = ui.get_ref().as_raw_fd();
                Some((r, w, w))
            },
            Interface::RWPair(_) => None,
            // NOTE: not supported yet
            #[cfg(feature="network")]
            Interface::Tls(_) => None,
            #[cfg(all(unix, feature="network"))]
            Interface::Ipc(ref ui) => {
                let fd = ui.get_ref().as_raw_fd();
                Some((fd, fd, fd))
            },
            Interface::Dummy(_) => None,
        }
    }
}

impl Read for Interface {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            #[cfg(feature="readline")]
            Interface::Fancy(ref mut x) => x.0.read(buf),
            Interface::Stdio(ref mut x) => x.read(buf),
            Interface::File(ref mut x) => x.read(buf),
            Interface::RWPair(ref mut x) => x.read(buf),
            #[cfg(feature="network")]
            Interface::Tls(ref mut x) => x.read(buf),
            #[cfg(all(unix, feature="network"))]
            Interface::Ipc(ref mut x) => x.read(buf),
            Interface::Dummy(ref mut _x) => unimplemented!(),
        }
    }
}

impl Write for Interface {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match *self {
            #[cfg(feature="readline")]
            Interface::Fancy(ref mut x) => x.1.write(buf),
            Interface::Stdio(ref mut x) => x.write(buf),
            Interface::File(ref mut x) => x.write(buf),
            Interface::RWPair(ref mut x) => x.write(buf),
            #[cfg(feature="network")]
            Interface::Tls(ref mut x) => x.write(buf),
            #[cfg(all(unix, feature="network"))]
            Interface::Ipc(ref mut x) => x.write(buf),
            Interface::Dummy(ref mut x) => x.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match *self {
            #[cfg(feature="readline")]
            Interface::Fancy(ref mut x) => x.1.flush(),
            Interface::Stdio(ref mut x) => x.flush(),
            Interface::File(ref mut x) => x.flush(),
            Interface::RWPair(ref mut x) => x.flush(),
            #[cfg(feature="network")]
            Interface::Tls(ref mut x) => x.flush(),
            #[cfg(all(unix, feature="network"))]
            Interface::Ipc(ref mut x) => x.flush(),
            Interface::Dummy(ref mut x) => x.flush(),
        }
    }
}