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
use std::io::{self, stdin, stdout};
use std::io::{Error, Read, Write};

use http_connection::HttpConnection;
use hyper::client::connect::{Connect, Connected, Destination};
use tokio::prelude::*;
use tokio::reactor::PollEvented2;

pub struct StdioSocket {
    reader: PollEvented2<async_stdio::EventedStdin>,
    writer: PollEvented2<async_stdio::EventedStdout>,
}

impl StdioSocket {
    pub fn try_new() -> io::Result<Self> {
        Ok(StdioSocket {
            reader: PollEvented2::new(async_stdio::EventedStdin::try_new(stdin())?),
            writer: PollEvented2::new(async_stdio::EventedStdout::try_new(stdout())?),
        })
    }
}

pub struct StdioConnector;

impl Read for StdioSocket {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        self.reader.read(buf)
    }
}

impl Write for StdioSocket {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
        self.writer.write(buf)
    }

    fn flush(&mut self) -> Result<(), Error> {
        self.writer.flush()
    }
}

impl AsyncRead for StdioSocket {}

impl AsyncWrite for StdioSocket {
    fn shutdown(&mut self) -> Result<Async<()>, Error> {
        self.writer.shutdown()
    }
}

impl HttpConnection for StdioSocket {}

impl Connect for StdioConnector {
    type Transport = StdioSocket;
    type Error = io::Error;
    type Future = future::FutureResult<(Self::Transport, Connected), io::Error>;

    fn connect(&self, _: Destination) -> Self::Future {
        future::result(StdioSocket::try_new().map(|socket| (socket, Connected::new())))
    }
}

mod async_stdio {
    use std::io::{self, Read, Stdin, Stdout, Write};
    use std::os::unix::io::AsRawFd;

    use mio::event::Evented;
    use mio::unix::EventedFd;
    use mio::{Poll, PollOpt, Ready, Token};

    use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};

    pub struct EventedStdin(Stdin);
    pub struct EventedStdout(Stdout);

    impl EventedStdin {
        pub fn try_new(stdin: Stdin) -> io::Result<Self> {
            set_non_blocking_flag(&stdin)?;
            Ok(EventedStdin(stdin))
        }
    }

    impl EventedStdout {
        pub fn try_new(stdout: Stdout) -> io::Result<Self> {
            set_non_blocking_flag(&stdout)?;
            Ok(EventedStdout(stdout))
        }
    }

    impl Evented for EventedStdin {
        fn register(
            &self,
            poll: &Poll,
            token: Token,
            interest: Ready,
            opts: PollOpt,
        ) -> io::Result<()> {
            EventedFd(&self.0.as_raw_fd()).register(poll, token, interest, opts)
        }

        fn reregister(
            &self,
            poll: &Poll,
            token: Token,
            interest: Ready,
            opts: PollOpt,
        ) -> io::Result<()> {
            EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest, opts)
        }

        fn deregister(&self, poll: &Poll) -> io::Result<()> {
            EventedFd(&self.0.as_raw_fd()).deregister(poll)
        }
    }

    impl Read for EventedStdin {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            self.0.read(buf)
        }
    }

    impl Evented for EventedStdout {
        fn register(
            &self,
            poll: &Poll,
            token: Token,
            interest: Ready,
            opts: PollOpt,
        ) -> io::Result<()> {
            EventedFd(&self.0.as_raw_fd()).register(poll, token, interest, opts)
        }

        fn reregister(
            &self,
            poll: &Poll,
            token: Token,
            interest: Ready,
            opts: PollOpt,
        ) -> io::Result<()> {
            EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest, opts)
        }

        fn deregister(&self, poll: &Poll) -> io::Result<()> {
            EventedFd(&self.0.as_raw_fd()).deregister(poll)
        }
    }

    impl Write for EventedStdout {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.write(buf)
        }

        fn flush(&mut self) -> io::Result<()> {
            self.0.flush()
        }
    }

    fn set_non_blocking_flag<T: AsRawFd>(stream: &T) -> io::Result<()> {
        let flags = unsafe { fcntl(stream.as_raw_fd(), F_GETFL, 0) };

        if flags < 0 {
            return Err(std::io::Error::last_os_error());
        }

        if unsafe { fcntl(stream.as_raw_fd(), F_SETFL, flags | O_NONBLOCK) } != 0 {
            return Err(std::io::Error::last_os_error());
        }

        Ok(())
    }
}