etunnel 1.4.0

Expose local services to the internet in one line of code: instant public HTTPS URLs with automatic TLS, through NAT and firewalls, no signup. Webhook-friendly ngrok-style reverse tunnel, with SDKs in 20 languages and a single-binary Go server.
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// etunnel SDK for Rust (tungstenite + ureq).
// Buffer-based protocol client (bodies buffered per stream; no WS upgrades).
use std::collections::HashMap;
use std::io::Read;
use std::net::TcpStream;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;

use tungstenite::client::IntoClientRequest;
use tungstenite::handshake::client::Response;
use tungstenite::protocol::{Message, WebSocketConfig};
use tungstenite::stream::MaybeTlsStream;

const MAXP: usize = 32768;

pub struct Options {
    pub token: Option<String>,
    pub subdomain: Option<String>,
}

pub struct Tunnel {
    pub url: String,
    /// Server-signed resume token: pass it back on reconnect to reclaim the
    /// same subdomain instead of getting a fresh random one.
    pub resume_token: String,
    /// Set once the reader loop sees the connection end (error, close or bye).
    /// The CLI supervisor polls it to decide when to reconnect.
    pub closed: Arc<AtomicBool>,
}

impl Tunnel {
    /// Dropping the tunnel process / task ends the connection; the server
    /// detects the closed socket and frees the subdomain.
    pub fn close(&self) {}
}

fn frame(kind: u8, sid: u32, payload: &[u8]) -> Message {
    let mut b = Vec::with_capacity(9 + payload.len());
    b.push(kind);
    b.extend_from_slice(&sid.to_be_bytes());
    b.extend_from_slice(&(payload.len() as u32).to_be_bytes());
    b.extend_from_slice(payload);
    Message::Binary(b.into())
}

// Minimal JSON helpers (control messages are simple, hand-rolled is enough).
fn json_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n")
}

fn extract_str(json: &str, key: &str) -> Option<String> {
    let pat = format!("\"{}\":", key);
    let i = json.find(&pat)? + pat.len();
    let rest = &json[i..];
    let rest = rest.trim_start();
    if !rest.starts_with('"') {
        return None;
    }
    let mut out = String::new();
    let mut chars = rest[1..].chars();
    while let Some(c) = chars.next() {
        match c {
            '"' => break,
            '\\' => match chars.next() {
                Some('n') => out.push('\n'),
                Some('t') => out.push('\t'),
                Some(o) => out.push(o),
                None => break,
            },
            o => out.push(o),
        }
    }
    Some(out)
}

fn extract_num(json: &str, key: &str) -> Option<f64> {
    let pat = format!("\"{}\":", key);
    let i = json.find(&pat)? + pat.len();
    let rest = json[i..].trim_start();
    let end = rest
        .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-'))
        .unwrap_or(rest.len());
    rest[..end].parse().ok()
}

// Very small header-map extractor for req messages: "headers":{"K":["v"],...}
fn extract_headers(json: &str) -> HashMap<String, Vec<String>> {
    let mut out = HashMap::new();
    let Some(hstart) = json.find("\"headers\":{") else { return out };
    let body = &json[hstart + 11..];
    // walk pairs until the matching close brace (naive but messages are flat)
    let bytes = body.as_bytes();
    let mut i = 0usize;
    let mut depth = 1usize;
    let mut cur_key = String::new();
    let mut cur_vals: Vec<String> = Vec::new();
    let mut in_key = false;
    let mut in_val = false;
    let mut buf = String::new();
    while i < bytes.len() {
        let c = bytes[i] as char;
        match c {
            '"' => {
                if in_key || in_val {
                    if in_key { cur_key = buf.clone(); } else { cur_vals.push(buf.clone()); }
                    buf.clear();
                    in_key = false;
                    in_val = false;
                } else if cur_key.is_empty() {
                    in_key = true;
                } else {
                    in_val = true;
                }
            }
            '{' | '[' => depth += 1,
            '}' | ']' => {
                depth -= 1;
                if depth == 0 {
                    if !cur_key.is_empty() {
                        out.insert(cur_key.clone(), cur_vals.clone());
                    }
                    break;
                }
            }
            ',' if depth == 1 && !cur_key.is_empty() && cur_vals.is_empty() => {
                // next key after value list ends is handled by ':' ... fallthrough
            }
            ':' if depth == 1 && !cur_key.is_empty() && cur_vals.is_empty() => {}
            _ => {
                if in_key || in_val {
                    buf.push(c);
                }
            }
        }
        i += 1;
    }
    out
}

struct StreamBuf {
    method: String,
    path: String,
    headers: HashMap<String, Vec<String>>,
    body: Vec<u8>,
}

pub fn connect(server: &str, local_port: u16, token: Option<&str>, subdomain: Option<&str>) -> Result<Tunnel, String> {
    connect_full(server, &format!("127.0.0.1:{}", local_port), token, subdomain)
}

pub fn connect_full(server: &str, local_addr: &str, token: Option<&str>, subdomain: Option<&str>) -> Result<Tunnel, String> {
    connect_full_resume(server, local_addr, token, subdomain, None)
}

/// Like [`connect_full`], plus an optional resume token from a previous
/// session so the server hands back the same subdomain after a drop.
pub fn connect_full_resume(server: &str, local_addr: &str, token: Option<&str>, subdomain: Option<&str>, resume: Option<&str>) -> Result<Tunnel, String> {
    let mut request = server
        .into_client_request()
        .map_err(|e| format!("bad url: {}", e))?;
    request.headers_mut().insert(
        "Sec-WebSocket-Protocol",
        "etunnel-v1".parse().unwrap(),
    );
    let cfg = WebSocketConfig::default();

    let _ = cfg;
    let (ws, _resp) = tungstenite::connect(request)
        .map_err(|e| format!("connect: {}", e))?;

    let ws = Arc::new(Mutex::new(ws));

    let mut hello = String::from("{\"type\":\"hello\",\"proto\":1");
    if let Some(s) = subdomain {
        hello.push_str(&format!(",\"subdomain\":\"{}\"", json_escape(s)));
    }
    if let Some(t) = token {
        hello.push_str(&format!(",\"token\":\"{}\"", json_escape(t)));
    }
    if let Some(r) = resume {
        if !r.is_empty() {
            hello.push_str(&format!(",\"resume\":\"{}\"", json_escape(r)));
        }
    }
    hello.push_str(",\"client\":\"etunnel-rust/1.0\"}");
    ws.lock().unwrap().send(Message::Text(hello.into())).ok();

    let mut url = String::new();
    let mut resume_token = String::new();
    loop {
        let msg = ws.lock().unwrap().read().map_err(|e| format!("read welcome: {}", e))?;
        if let Message::Text(t) = msg {
            let t = t.as_str();
            if let Some(u) = extract_str(t, "url") {
                if t.contains("\"type\":\"welcome\"") {
                    url = u;
                    resume_token = extract_str(t, "resumeToken").unwrap_or_default();
                    break;
                }
            }
            if t.contains("\"type\":\"error\"") {
                let code = extract_str(t, "code").unwrap_or_default();
                return Err(format!("etunnel: {}", code));
            }
        }
    }

    let closed = Arc::new(AtomicBool::new(false));
    let ws2 = Arc::clone(&ws);
    let local = local_addr.to_string();
    let closed2 = Arc::clone(&closed);
    thread::spawn(move || {
        let mut streams: HashMap<u32, StreamBuf> = HashMap::new();
        loop {
            let msg = {
                let mut w = ws2.lock().unwrap();
                match w.read() {
                    Ok(m) => m,
                    Err(_) => break,
                }
            };
            match msg {
                Message::Text(t) => {
                    let t = t.as_str().to_string();
                    if t.contains("\"type\":\"req\"") {
                        let sid = extract_num(&t, "streamId").unwrap_or(0.0) as u32;
                        streams.insert(sid, StreamBuf {
                            method: extract_str(&t, "method").unwrap_or_else(|| "GET".into()),
                            path: extract_str(&t, "path").unwrap_or_else(|| "/".into()),
                            headers: extract_headers(&t),
                            body: Vec::new(),
                        });
                    } else if t.contains("\"type\":\"ping\"") {
                        let ts = extract_num(&t, "ts").unwrap_or(0.0) as i64;
                        let mut w = ws2.lock().unwrap();
                        w.send(Message::Text(format!("{{\"type\":\"pong\",\"ts\":{}}}", ts).into())).ok();
                    } else if t.contains("\"type\":\"bye\"") {
                        break;
                    }
                }
                Message::Binary(b) => {
                    if b.len() < 9 { continue; }
                    let kind = b[0];
                    let sid = u32::from_be_bytes([b[1], b[2], b[3], b[4]]);
                    let n = u32::from_be_bytes([b[5], b[6], b[7], b[8]]) as usize;
                    let payload = &b[9..(9 + n).min(b.len())];
                    let Some(st) = streams.get_mut(&sid) else { continue };
                    match kind {
                        0x01 => st.body.extend_from_slice(payload),
                        0x02 => {
                            let st = streams.remove(&sid).unwrap();
                            let ws3 = Arc::clone(&ws2);
                            let local3 = local.clone();
                            thread::spawn(move || serve(ws3, local3, sid, st));
                        }
                        0x03 => { streams.remove(&sid); }
                        _ => {}
                    }
                }
                Message::Close(_) => break,
                _ => {}
            }
        }
        closed2.store(true, Ordering::SeqCst);
    });

    Ok(Tunnel { url, resume_token, closed })
}

/// Themed 502 page shown when the local app is down (same HTML as the other SDKs).
const ERR_PAGE_A: &str = r##"<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>502 - local app down</title>
<style>
:root{--bg:#0b0e14;--panel:#0d1117;--line:#21262d;--fg:#e6edf3;--dim:#8b949e;--green:#3fb950}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:ui-monospace,'SF Mono',Menlo,Consolas,monospace;background:var(--bg);color:var(--fg);
display:flex;min-height:100vh;align-items:center;justify-content:center;line-height:1.6}
main{max-width:600px;padding:2.5rem 1.5rem;width:100%}
.badge{display:inline-block;border:1px solid rgba(248,81,73,.4);color:#f85149;border-radius:99px;
padding:.2rem .8rem;font-size:.72rem;letter-spacing:.08em;text-transform:uppercase;margin-bottom:1.1rem}
h1{font-size:1.6rem;letter-spacing:-.01em;margin-bottom:.4rem}
h1 .g{color:var(--green)}
p{color:var(--dim);font-size:.9rem;margin-bottom:1.4rem}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:1.1rem 1.3rem;margin-bottom:1.1rem}
.panel .k{color:var(--dim);font-size:.72rem;text-transform:uppercase;letter-spacing:.08em;margin-bottom:.3rem}
.panel .v{font-size:.9rem;word-break:break-all}
.err{color:#f85149}
.tip{border-left:3px solid var(--green);padding:.8rem 1rem;margin-top:1.2rem;font-size:.82rem;color:var(--dim)}
.tip b{color:var(--fg)}
footer{margin-top:2rem;font-size:.75rem;color:var(--dim)}
footer a{color:#58a6ff;text-decoration:none}
.pulse{display:inline-block;width:.55em;height:.55em;border-radius:50%;background:var(--green);
margin-right:.5em;animation:p 1.2s ease-in-out infinite}
@keyframes p{0%,100%{opacity:1}50%{opacity:.25}}
@media(prefers-reduced-motion:reduce){.pulse{animation:none}}
</style></head><body><main>
<span class="badge">502 local app down</span>
<h1>tunnel up, <span class="g">local app</span> is not</h1>
<p>The tunnel connection is alive, but nothing answered when we knocked.</p>
<div class="panel">
<div class="k">error</div><div class="v err">"##;

const ERR_PAGE_B: &str = r##"</div>
</div>
<div class="tip"><span class="pulse"></span><b>Fix:</b> start your local service and reload -
the tunnel stays connected and keeps retrying for you.</div>
<footer>powered by <a href="https://github.com/topcheer/etunnel">etunnel</a></footer>
</main></body></html>"##;

fn escape_html(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

fn local_error_page(msg: &str) -> String {
    format!("{}{}{}", ERR_PAGE_A, escape_html(msg), ERR_PAGE_B)
}

fn serve(ws: Arc<Mutex<tungstenite::WebSocket<MaybeTlsStream<TcpStream>>>>, local: String, sid: u32, st: StreamBuf) {
    let hop = |k: &str| {
        matches!(k.to_ascii_lowercase().as_str(), "connection" | "transfer-encoding" | "keep-alive"
            | "upgrade" | "content-length" | "host" | "proxy-connection" | "te" | "trailer")
    };
    let mut req = ureq::request(&st.method, &format!("http://{}{}", local, st.path));
    for (k, vs) in &st.headers {
        if hop(k) { continue; }
        for v in vs {
            req = req.set(k, v);
        }
    }
    let body = st.body.clone();
    let resp = if st.method == "GET" || st.method == "HEAD" {
        req.call()
    } else {
        req.send_bytes(&body)
    };

    let (status, headers, out) = match resp {
        Ok(r) => {
            let status = r.status();
            let mut hdrs: Vec<(String, String)> = Vec::new();
            for name in r.headers_names() {
                if hop(&name) { continue; }
                if let Some(v) = r.header(&name) {
                    hdrs.push((name, v.to_string()));
                }
            }
            let mut buf = Vec::new();
            r.into_reader().take(64 * 1024 * 1024).read_to_end(&mut buf).unwrap_or(0);
            (status, hdrs, buf)
        }
        Err(ureq::Error::Status(code, r)) => {
            let mut buf = Vec::new();
            r.into_reader().read_to_end(&mut buf).unwrap_or(0);
            (code, Vec::new(), buf)
        }
        Err(e) => {
            let mut w = ws.lock().unwrap();
            w.send(Message::Text(format!(
                "{{\"type\":\"res\",\"streamId\":{},\"status\":502,\"headers\":{{\"Content-Type\":[\"text/html; charset=utf-8\"]}}}}", sid).into())).ok();
            w.send(frame(0x01, sid, local_error_page(&e.to_string()).as_bytes())).ok();
            w.send(frame(0x02, sid, b"")).ok();
            return;
        }
    };

    let hdr_json = headers
        .iter()
        .map(|(k, v)| format!("\"{}\":[\"{}\"]", json_escape(k), json_escape(v)))
        .collect::<Vec<_>>()
        .join(",");
    let mut w = ws.lock().unwrap();
    w.send(Message::Text(format!(
        "{{\"type\":\"res\",\"streamId\":{},\"status\":{},\"headers\":{{{}}}}}", sid, status, hdr_json).into())).ok();
    for chunk in out.chunks(MAXP) {
        w.send(frame(0x01, sid, chunk)).ok();
    }
    w.send(frame(0x02, sid, b"")).ok();
}

fn backoff_ms(attempt: u32) -> u64 {
    // 500ms, 1s, 2s, ... capped at 30s, then ±20% jitter.
    let base = (500u64 << attempt.min(6)).min(30_000);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    base * (800 + nanos % 401) / 1000
}

fn main() {
    let server = std::env::var("ETUNNEL_SERVER").unwrap_or_else(|_| option_env!("ETUNNEL_BUILD_SERVER").unwrap_or("wss://t.etun.uk/tunnel").into());
    let local = std::env::args().nth(1)
        .or_else(|| std::env::var("ETUNNEL_LOCAL").ok())
        .unwrap_or_else(|| "3000".into());
    let local = if local.contains(':') { local } else { format!("127.0.0.1:{}", local) };
    let (host, port) = local.rsplit_once(':').unwrap();
    let port: u16 = port.parse().unwrap_or(3000);
    let local = format!("{}:{}", host, port);
    let token = std::env::var("ETUNNEL_TOKEN").ok();
    let subdomain = std::env::var("ETUNNEL_SUBDOMAIN").ok();
    // ETUNNEL_RECONNECT=0 restores the one-shot behaviour (exit on first error).
    let reconnect = std::env::var("ETUNNEL_RECONNECT").map(|v| v != "0").unwrap_or(true);

    // SIGINT/SIGTERM keep their default disposition: the process dies at once,
    // so a stopped CLI never reconnects.
    let mut attempt: u32 = 0;
    // Carried across drops so a reconnect reclaims the same subdomain.
    let mut resume: Option<String> = None;
    loop {
        match connect_full_resume(
            &server,
            &local,
            token.as_deref(),
            subdomain.as_deref(),
            resume.as_deref(),
        ) {
            Ok(t) => {
                println!("TUNNEL_URL: {}", t.url);
                attempt = 0;
                if !t.resume_token.is_empty() {
                    resume = Some(t.resume_token.clone());
                }
                if !reconnect {
                    loop { thread::sleep(std::time::Duration::from_secs(3600)); }
                }
                while !t.closed.load(Ordering::SeqCst) {
                    thread::sleep(std::time::Duration::from_millis(200));
                }
                eprintln!("etunnel: connection lost, reconnecting");
            }
            Err(e) => {
                eprintln!("etunnel: {}", e);
                if !reconnect {
                    std::process::exit(1);
                }
            }
        }
        let delay = backoff_ms(attempt);
        attempt = attempt.saturating_add(1);
        eprintln!("etunnel: reconnect in {}ms", delay);
        thread::sleep(std::time::Duration::from_millis(delay));
    }
}