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
//! # Ngrok
//!
//! A minimal and concise [`ngrok`](https://ngrok.com/) wrapper for Rust. The main use case for the library
//! is the ability to open public HTTP tunnels to your development server(s) for
//! integrations tests. TCP support, while not available, should be trivial to support.
//!
//! This has been tested with Linux and assume that it does not work on Windows (contributions
//! welcome).
//!
//! ## Usage
//! ```
//! fn main() -> std::io::Result<()> {
//!     let tunnel = ngrok::builder()
//!           // server protocol
//!           .http()
//!           // the port
//! #         .executable("./ngrok")
//!           .port(3030)
//!           .run()?;
//!
//!     let public_url = tunnel.http()?;
//!
//!     Ok(())
//! }
//! ```

use std::process::Child;
use std::sync::Arc;
use std::sync::Mutex;
use std::{fmt, io, process::Command, process::Stdio, thread, time::Duration, time::Instant};
use thiserror::Error;
use url::Url;

#[derive(Error, Debug)]
enum Error {
    #[error("Unexpected JSON found in `ngrok`'s JSON API")]
    MalformedAPIResponse,

    #[error("Expected a matching tunnel but found none under `ngrok`'s JSON API @ http://localhost:4040/api/tunnels")]
    TunnelNotFound,

    #[error("Builder expected `{0}`")]
    BuilderError(&'static str),

    #[error("Tunnel exited unexpectedly with exit status `{0}`")]
    TunnelProcessExited(String),
}

impl From<Error> for io::Error {
    fn from(err: Error) -> Self {
        io::Error::new(io::ErrorKind::Other, err)
    }
}

type Resource = Arc<Mutex<Child>>;

/// A running `ngrok` Tunnel.
#[derive(Debug, Clone)]
pub struct Tunnel {
    pub(crate) proc: Resource,
    /// The tunnel's public URL
    tunnel_http: url::Url,
    /// The tunnel's public URL
    tunnel_https: url::Url,
}

impl AsRef<url::Url> for Tunnel {
    fn as_ref(&self) -> &url::Url {
        &self.tunnel_http
    }
}

impl fmt::Display for Tunnel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.tunnel_http.fmt(f)
    }
}

impl Tunnel {
    /// Build a new `ngrok` Tunnel
    pub fn builder() -> Builder {
        crate::builder()
    }

    /// Determine if the underlying child process has exited
    /// and return the exit error if so.
    pub fn status(&self) -> Result<(), io::Error> {
        let status = { self.proc.lock().unwrap().try_wait()? };

        match status {
            Some(code) => Err(io::Error::from(Error::TunnelProcessExited(
                code.to_string(),
            ))),
            _ => Ok(()),
        }
    }

    /// Retrieve the tunnel's http URL. If the underlying process has terminated,
    /// this will return the exit status
    pub fn http(&self) -> Result<&Url, io::Error> {
        self.status()?;
        Ok(&self.tunnel_http)
    }

    /// Retrieve the tunnel's https URL. If the underlying process has terminated,
    /// this will return the exit status
    pub fn https(&self) -> Result<&Url, io::Error> {
        self.status()?;
        Ok(&self.tunnel_https)
    }

    /// Retrieve the tunnel's http URL.
    pub fn http_unchecked(&self) -> &Url {
        &self.tunnel_http
    }

    /// Retrieve the tunnel's https URL.
    pub fn https_unchecked(&self) -> &Url {
        &self.tunnel_https
    }
}

impl Drop for Tunnel {
    /// Stop the Ngrok child process
    fn drop(&mut self) {
        let _result = self.proc.lock().unwrap().kill();
    }
}

/// Build a `ngrok` Tunnel. Use `ngrok::builder()` to create this.
#[derive(Debug, Clone, Default)]
pub struct Builder {
    http: Option<()>,
    port: Option<u16>,
    executable: Option<String>,
}

/// The entry point for starting a `ngrok` tunnel. Only HTTP is currently supported.
///
/// **Example**
///
/// ```
/// ngrok::builder()
///         .executable("./ngrok")
///         .http()
///         .port(3031)
///         .run()
///         .unwrap();
/// ```
pub fn builder() -> Builder {
    Builder {
        ..Default::default()
    }
}

impl Builder {
    /// Create a new `Builder`
    pub fn new() -> Self {
        Builder {
            ..Default::default()
        }
    }

    /// Set the tunnel protocol to HTTP
    pub fn http(&mut self) -> Self {
        self.http = Some(());
        self.clone()
    }

    /// Set the tunnel port
    pub fn port(&mut self, port: u16) -> Self {
        self.port = Some(port);
        self.clone()
    }

    /// Set the `ngrok` executable path. By default the builder
    /// assumes `ngrok` is on your path.
    pub fn executable(&mut self, executable: &str) -> Self {
        self.executable = Some(executable.to_string());
        self.clone()
    }

    /// Start the `ngrok` child process. Note this is a blocking call
    /// and it will sleep for several seconds.
    // There is a detached thread that waits for either
    // A: the Ngrok instance to drop, which in `impl Drop` sends a message over
    // the channel, or
    // B: the underlying process to quit
    pub fn run(self) -> Result<Tunnel, io::Error> {
        // Prepare for TCP/other
        let _http = self
            .http
            .ok_or(Error::BuilderError(".http() should have been called"))?;

        let port = self
            .port
            .ok_or(Error::BuilderError(".port(port) should have been set"))?;

        let started_at = Instant::now();

        // Start the `ngrok` process
        let proc = Command::new(self.executable.unwrap_or_else(|| "ngrok".to_string()))
            .stdout(Stdio::piped())
            .arg("http")
            .arg(port.to_string())
            .spawn()?;

        // ngrok takes a bit to start up and this is a (probably bad) way to wait
        // for the tunnel to appear:
        let (tunnel_http, tunnel_https) = {
            loop {
                let tunnels = find_tunnels(port);
                if tunnels.is_ok() {
                    break tunnels;
                }

                // If 5 seconds have elapsed, mission failed
                if started_at.elapsed().as_secs() > 5 {
                    break tunnels;
                }

                // Elsewise try again in 300 millis
                thread::sleep(Duration::from_millis(300));
            }
        }?;

        Ok(Tunnel {
            tunnel_http,
            tunnel_https,
            proc: Arc::new(Mutex::new(proc)),
        })
    }
}

fn find_tunnels(port: u16) -> Result<(url::Url, url::Url), io::Error> {
    use serde_json::Value;

    // Retrieve the `tunnel_url`
    let response: Value = ureq::get("http://localhost:4040/api/tunnels")
        .call()
        .into_json()?;

    let tunnels = response
        .get("tunnels")
        .and_then(|tunnels| tunnels.as_array())
        .map(Ok)
        .unwrap_or(Err(Error::MalformedAPIResponse))?;

    // snag both HTTP/HTTPS urls
    fn find_tunnel_url<'a, I: IntoIterator<Item = &'a Value>>(
        scheme: &'static str,
        port: u16,
        iter: I,
    ) -> Result<url::Url, Error> {
        for tunnel in iter {
            let tunnel_url = tunnel.get("public_url").and_then(|url| url.as_str());

            let is_port = tunnel
                .get("config")
                .and_then(|cfg| cfg.get("addr"))
                .and_then(|addr| addr.as_str())
                .map(|addr| addr.contains(&port.to_string()))
                .unwrap_or(false);

            let is_scheme = tunnel_url.map(|url| url.contains(scheme)).unwrap_or(false);

            if is_scheme && is_port {
                return Ok(url::Url::parse(tunnel_url.unwrap())
                    .map_err(|_| Error::MalformedAPIResponse)?);
            }
        }

        Err(Error::TunnelNotFound)
    }

    let tunnel_http = find_tunnel_url("http://", port, tunnels)?;
    let tunnel_https = find_tunnel_url("https://", port, tunnels)?;

    Ok((tunnel_http, tunnel_https))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_status_if_proc_killed() {
        let tunnel = builder()
            .executable("./ngrok")
            .http()
            .port(3000)
            .run()
            .unwrap();
        tunnel.proc.lock().unwrap().kill().unwrap();
        std::thread::sleep(Duration::from_millis(2500));
        assert!(tunnel.http().is_err())
    }

    #[tokio::test(threaded_scheduler)]
    async fn test_proxy_to_local_server() {
        use warp::Filter;

        let routes = warp::any().map(|| warp::reply());

        let handle =
            tokio::task::spawn(
                async move { warp::serve(routes).run(([127, 0, 0, 1], 3060)).await },
            );

        let tunnel = builder()
            .executable("./ngrok")
            .http()
            .port(3060)
            .run()
            .unwrap();

        let status = ureq::get(tunnel.http().unwrap().as_str()).call().status();
        assert_eq!(status, 200);

        drop(handle)
    }
}