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
// Copyright 2018 Peter Williams <peter@newton.cx>
// Licensed under the MIT License.

//! Communication with the daemon.
//!
//! This module provides the [`Connection`] type, which provides a
//! programmatic interface to requests that clients may make of the stund
//! server.

use failure::{Error, ResultExt};
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use futures::sink::Send;
use libc;
use state_machine_future::RentToOwn;
use std::env;
use std::io;
use std::mem;
use std::process;
use std::thread;
use std::time;
use std::os::unix::io::AsRawFd;
use tokio_core::reactor::Core;
use tokio_uds::UnixStream;

use super::*;
use codecs::{self, Deserializer, Serializer};

type Ser = Serializer<ClientMessage>;
type De = Deserializer<ServerMessage>;
type UserInputStream = Box<Stream<Item = Vec<u8>, Error = io::Error>>;
type UserOutputSink = Box<Sink<SinkItem = Vec<u8>, SinkError = io::Error>>;


/// A connection the stund daemon.
pub struct Connection {
    core: Core,
    ser: Ser,
    de: De,
}

impl Connection {
    fn establish_inner(autolaunch: bool) -> Result<Option<Self>, Error> {
        let core = Core::new().context("couldn't create IO core?")?;
        let handle = core.handle();
        let sock_path = get_socket_path().context("couldn't get path to talk to daemon")?;

        let conn = match UnixStream::connect(&sock_path, &handle) {
            Ok(c) => c,
            Err(_e) => {
                if !autolaunch { // should we care about what the error is exatly?
                    return Ok(None);
                }

                let curr_exe = env::current_exe().context("couldn't get current executable path")?;

                let status = process::Command::new(&curr_exe)
                    .arg("daemon")
                    .status()
                    .context("daemon launcher reported failure")?;

                thread::sleep(time::Duration::from_millis(300));

                if status.success() {
                    UnixStream::connect(&sock_path, &handle)
                        .context("failed to connect to daemon even after launching it")?
                } else {
                    return Err(format_err!("failed to launch background daemon"));
                }
            },
        };

        unsafe {
            // Without turning on linger, I find that the tokio-ized version
            // loses the last bytes of the session. Let's just ignore the
            // return value of setsockopt(), though.
            let linger = libc::linger { l_onoff: 1, l_linger: 2 };
            libc::setsockopt(conn.as_raw_fd(), libc::SOL_SOCKET, libc::SO_LINGER,
                             (&linger as *const libc::linger) as _,
                             mem::size_of::<libc::linger>() as libc::socklen_t);
        }

        let (ser, de) = codecs::split(conn);

        Ok(Some(Connection {
            core: core,
            ser: ser,
            de: de,
        }))
    }

    /// Try to connect to the daemon.
    ///
    /// If the daemon is not running, returns `Ok(None)`.
    pub fn try_establish() -> Result<Option<Self>, Error> {
        Self::establish_inner(false)
    }

    /// Connect to the daemon, starting it if it is not already running.
    pub fn establish() -> Result<Self, Error> {
        Ok(Self::establish_inner(true)?.unwrap())
    }

    /// Close the connection to the daemon.
    ///
    /// This operation conducts I/O because it sends a "Goodbye" message.
    pub fn close(mut self) -> Result<(), Error> {
        self.core.run(self.ser.send(ClientMessage::Goodbye))?;
        Ok(())
    }

    /// Tell the daemon to open a new SSH connection.
    ///
    /// Because the user may have to type a password or respond to some other
    /// prompt from the server to authenticate themselves, callers of this
    /// function must provide asynchronous I/O types implementing this user
    /// interaction.
    pub fn send_open<T, R>(
        mut self, params: OpenParameters, tx_user: T, rx_user: R
    ) -> Result<(OpenResult, Self), Error>
        where T: 'static + Sink<SinkItem = Vec<u8>, SinkError = io::Error>,
              R: 'static + Stream<Item = Vec<u8>, Error = io::Error>
    {
        let fut = self.ser.send(ClientMessage::Open(params));
        let wf = OpenWorkflow::start(fut, self.de, Box::new(tx_user), Box::new(rx_user));
        let (ser, de, result) = self.core.run(wf)?;
        self.ser = ser;
        self.de = de;
        Ok((result, self))
    }

    /// Query the server’s status.
    ///
    /// At the moment, the only information that is returned is a list of
    /// connections that have been opened and their current state.
    pub fn query_status(mut self) -> Result<(StatusInformation, Self), Error> {
        let (ser, de) = (self.ser, self.de);

        let fut = ser.send(ClientMessage::QueryStatus)
            .map_err(|e| format_err!("error sending query-status message to daemon: {}", e))
            .and_then(move |ser| {
                de.into_future()
                    .map_err(|(e, _de)| format_err!("error receiving daemon reply: {}", e))
                    .map(|(maybe_msg, de)| (maybe_msg, ser, de))
            }).and_then(|(maybe_msg, ser, de)| {
                match maybe_msg {
                    Some(ServerMessage::StatusResponse(info)) => Ok((info, ser, de)),
                    Some(ServerMessage::Error(msg)) => return Err(format_err!("{}", msg)),
                    Some(other) => return Err(format_err!("unexpected server reply: {:?}", other)),
                    None => return Err(format_err!("unexpected disconnection from server")),
                }
            });

        let (info, ser, de) = self.core.run(fut)?;
        self.ser = ser;
        self.de = de;
        Ok((info, self))
    }

    /// Tell the server to close an existing tunnel.
    pub fn send_close(mut self, params: CloseParameters) -> Result<(CloseResult, Self), Error> {
        let (ser, de) = (self.ser, self.de);

        let fut = ser.send(ClientMessage::Close(params))
            .map_err(|e| format_err!("error sending close message to daemon: {}", e))
            .and_then(move |ser| {
                de.into_future()
                    .map_err(|(e, _de)| format_err!("error receiving daemon reply: {}", e))
                    .map(|(maybe_msg, de)| (maybe_msg, ser, de))
            }).and_then(|(maybe_msg, ser, de)| {
                match maybe_msg {
                    Some(ServerMessage::Ok) => Ok((CloseResult::Success, ser, de)),
                    Some(ServerMessage::TunnelNotOpen) => Ok((CloseResult::NotOpen, ser, de)),
                    Some(ServerMessage::Error(msg)) => return Err(format_err!("{}", msg)),
                    Some(other) => return Err(format_err!("unexpected server reply: {:?}", other)),
                    None => return Err(format_err!("unexpected disconnection from server")),
                }
            });

        let (result, ser, de) = self.core.run(fut)?;
        self.ser = ser;
        self.de = de;
        Ok((result, self))
    }

    /// Tell the server to exit.
    ///
    /// This, of course, means that all SSH tunnels will be closed. The server
    /// will not actually exit until the client sends its "Goodbye" message
    /// and disconnections.
    pub fn send_exit(mut self) -> Result<Self, Error> {
        let (ser, de) = (self.ser, self.de);

        let fut = ser.send(ClientMessage::Exit)
            .map_err(|e| format_err!("error sending exit message to daemon: {}", e))
            .and_then(move |ser| {
                de.into_future()
                    .map_err(|(e, _de)| format_err!("error receiving daemon reply: {}", e))
                    .map(|(maybe_msg, de)| (maybe_msg, ser, de))
            }).and_then(|(maybe_msg, ser, de)| {
                match maybe_msg {
                    Some(ServerMessage::Ok) => Ok((ser, de)),
                    Some(ServerMessage::Error(msg)) => return Err(format_err!("{}", msg)),
                    Some(other) => return Err(format_err!("unexpected server reply: {:?}", other)),
                    None => return Err(format_err!("unexpected disconnection from server")),
                }
            });

        let (ser, de) = self.core.run(fut)?;
        self.ser = ser;
        self.de = de;
        Ok(self)
    }
}


#[derive(StateMachineFuture)]
#[allow(unused)] // get lots of these spuriously; custom derive stuff?
enum OpenWorkflow {
    #[state_machine_future(start, transitions(FirstAck))]
    Issue {
        tx_ssh: Send<Ser>,
        rx_ssh: De,
        tx_user: UserOutputSink,
        rx_user: UserInputStream,
    },

    #[state_machine_future(transitions(Finished, Communicating))]
    FirstAck {
        tx_ssh: Ser,
        rx_ssh: De,
        tx_user: UserOutputSink,
        rx_user: UserInputStream,
        saw_ok: bool,
    },

    #[state_machine_future(transitions(Finished))]
    Communicating {
        tx_ssh: Ser,
        rx_ssh: De,
        ssh_buf: Vec<u8>,
        tx_user: UserOutputSink,
        rx_user: UserInputStream,
        user_buf: Vec<u8>,
    },

    #[state_machine_future(ready)]
    Finished((Ser, De, OpenResult)),

    #[state_machine_future(error)]
    Failed(Error),
}


impl PollOpenWorkflow for OpenWorkflow {
    fn poll_issue<'a>(
        state: &'a mut RentToOwn<'a, Issue>
    ) -> Poll<AfterIssue, Error> {
        let ser = try_ready!(state.tx_ssh.poll());

        let state = state.take();
        transition!(FirstAck {
            tx_ssh: ser,
            rx_ssh: state.rx_ssh,
            tx_user: state.tx_user,
            rx_user: state.rx_user,
            saw_ok: false,
        })
    }

    fn poll_first_ack<'a>(
        state: &'a mut RentToOwn<'a, FirstAck>
    ) -> Poll<AfterFirstAck, Error> {
        while let Async::Ready(msg) = state.rx_ssh.poll()? {
            match msg {
                Some(ServerMessage::Ok) => {
                    state.saw_ok = true;
                },

                Some(ServerMessage::Error(text)) => {
                    return Err(format_err!("{}", text));
                },

                Some(ServerMessage::TunnelAlreadyOpen) => {
                    let state = state.take();
                    transition!(Finished((state.tx_ssh, state.rx_ssh, OpenResult::AlreadyOpen)));
                },

                Some(other) => {
                    return Err(format_err!("unexpected response from daemon: {:?}", other));
                },

                None => {
                    return Err(format_err!("connection closed (?)"));
                },
            }
        }

        if state.saw_ok {
            let state = state.take();

            transition!(Communicating {
                rx_user: state.rx_user,
                tx_user: state.tx_user,
                user_buf: Vec::new(),
                tx_ssh: state.tx_ssh,
                rx_ssh: state.rx_ssh,
                ssh_buf: Vec::new(),
            })
        }

        Ok(Async::NotReady)
    }

    fn poll_communicating<'a>(
        state: &'a mut RentToOwn<'a, Communicating>
    ) -> Poll<AfterCommunicating, Error> {
        // News from the daemon?

        while let Async::Ready(msg) = state.rx_ssh.poll()? {
            match msg {
                Some(ServerMessage::SshData(data)) => {
                    state.user_buf.extend_from_slice(&data);
                },

                Some(ServerMessage::Ok) => {
                    // All done!
                    let mut state = state.take();
                    transition!(Finished((state.tx_ssh, state.rx_ssh, OpenResult::Success)));
                },

                Some(ServerMessage::Error(e)) => {
                    return Err(format_err!("{}", e));
                }

                Some(other) => {
                    return Err(format_err!("unexpected message from the daemon: {:?}", other));
                },

                None => {},
            }
        }

        // New text from the user?

        while let Async::Ready(bytes) = state.rx_user.poll()? {
            match bytes {
                None => {
                    // EOF on the user input. This can happen in --no-input mode or,
                    // in principle, if stdin is redirected in some way.
                    break;
                },

                Some(b) => {
                    state.ssh_buf.extend_from_slice(&b);
                }
            }
        }

        // Ready/able to send bytes to the user?

        if state.user_buf.len() != 0 {
            let buf = state.user_buf.clone();

            if let AsyncSink::Ready = state.tx_user.start_send(buf)? {
                    state.user_buf.clear();
            }
        }

        // Ready/able to send bytes to the daemon?

        if state.ssh_buf.len() != 0 {
            let buf = state.ssh_buf.clone();

            if let AsyncSink::Ready = state.tx_ssh.start_send(ClientMessage::UserData(buf))? {
                state.ssh_buf.clear();
            }
        }

        // Gotta flush those transmissions.

        try_ready!(state.tx_user.poll_complete());
        try_ready!(state.tx_ssh.poll_complete());
        Ok(Async::NotReady)
    }
}