1pub use burrow_core;
29
30use std::net::SocketAddr;
31use std::sync::Arc;
32use std::time::Duration;
33
34use anyhow::{Context, Result};
35use bytes::Bytes;
36use futures_util::stream::SplitSink;
37use futures_util::{SinkExt, StreamExt};
38use http_body_util::Full;
39use hyper::body::Incoming;
40use hyper::client::conn::http1;
41use hyper::{Request, Response};
42use hyper_util::rt::TokioIo;
43use tokio::net::TcpStream;
44use tokio::sync::{Mutex, watch};
45use tokio::task::JoinHandle;
46use tokio_tungstenite::tungstenite::Message;
47use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};
48use tracing::{error, info, warn};
49
50const BACKOFF_INITIAL: Duration = Duration::from_secs(1);
51const BACKOFF_MAX: Duration = Duration::from_secs(60);
52use burrow_core::{
53 ClientMessage, ServerMessage, TUNNEL_WS_PATH, TunnelError, TunnelFrame, TunnelRequest,
54 TunnelResponse, decode_frame, encode,
55};
56
57type WsSink = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>;
58
59pub struct TunnelHandle {
61 url: String,
62 _task: JoinHandle<()>,
63 shutdown_tx: watch::Sender<bool>,
64}
65
66impl TunnelHandle {
67 pub fn url(&self) -> &str {
69 &self.url
70 }
71
72 pub async fn close(self) {
74 let _ = self.shutdown_tx.send(true);
75 let _ = self._task.await;
76 }
77}
78
79pub struct TunnelClient {
81 server_url: String,
82 local_addr: SocketAddr,
83 token: Option<String>,
84 subdomain: Option<String>,
85}
86
87impl TunnelClient {
88 pub fn new(server_url: impl Into<String>, local_addr: SocketAddr) -> Self {
89 Self {
90 server_url: server_url.into(),
91 local_addr,
92 token: None,
93 subdomain: None,
94 }
95 }
96
97 pub fn token(mut self, token: impl Into<String>) -> Self {
99 self.token = Some(token.into());
100 self
101 }
102
103 pub fn subdomain(mut self, subdomain: impl Into<String>) -> Self {
105 self.subdomain = Some(subdomain.into());
106 self
107 }
108
109 pub async fn connect(self) -> Result<TunnelHandle> {
116 let ws_url = format!(
117 "{}/{}",
118 self.server_url.trim_end_matches('/'),
119 TUNNEL_WS_PATH.trim_start_matches('/')
120 );
121
122 info!(url = %ws_url, "connecting to tunnel server");
123
124 let (ws, _response) = connect_async(&ws_url)
125 .await
126 .context("failed to connect to tunnel server")?;
127
128 let (assigned_url, ws) = handshake(ws, self.token.clone(), self.subdomain.clone()).await?;
129
130 let (shutdown_tx, shutdown_rx) = watch::channel(false);
131 let local_addr = self.local_addr;
132 let url = assigned_url.clone();
133 let token = self.token;
134 let subdomain = self.subdomain;
135
136 let task = tokio::spawn(async move {
137 run_with_reconnect(ws, ws_url, token, subdomain, local_addr, shutdown_rx).await;
138 });
139
140 Ok(TunnelHandle {
141 url,
142 _task: task,
143 shutdown_tx,
144 })
145 }
146}
147
148async fn run_with_reconnect(
150 ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
151 ws_url: String,
152 token: Option<String>,
153 subdomain: Option<String>,
154 local_addr: SocketAddr,
155 mut shutdown_rx: watch::Receiver<bool>,
156) {
157 if let Err(e) = tunnel_loop(ws, local_addr, shutdown_rx.clone()).await {
159 error!(error = %e, "tunnel loop exited with error");
160 }
161
162 if *shutdown_rx.borrow() {
164 return;
165 }
166
167 let mut backoff = BACKOFF_INITIAL;
168
169 loop {
170 warn!(delay = ?backoff, "connection lost, reconnecting");
171
172 tokio::select! {
173 _ = shutdown_rx.changed() => {
174 info!("shutdown requested, stopping reconnection");
175 return;
176 }
177 _ = tokio::time::sleep(backoff) => {}
178 }
179
180 if *shutdown_rx.borrow() {
181 return;
182 }
183
184 match connect_async(&ws_url).await {
185 Ok((ws, _)) => match handshake(ws, token.clone(), subdomain.clone()).await {
186 Ok((_url, ws)) => {
187 info!("reconnected to tunnel server");
188 backoff = BACKOFF_INITIAL;
189
190 if let Err(e) = tunnel_loop(ws, local_addr, shutdown_rx.clone()).await {
191 error!(error = %e, "tunnel loop exited with error");
192 }
193
194 if *shutdown_rx.borrow() {
195 return;
196 }
197 }
198 Err(e) => {
199 error!(error = %e, "handshake failed after reconnect");
200 }
201 },
202 Err(e) => {
203 error!(error = %e, "reconnection failed");
204 }
205 }
206
207 backoff = (backoff * 2).min(BACKOFF_MAX);
208 }
209}
210
211async fn handshake(
213 mut ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
214 token: Option<String>,
215 subdomain: Option<String>,
216) -> Result<(String, WebSocketStream<MaybeTlsStream<TcpStream>>)> {
217 let hello = ClientMessage::Hello {
218 token,
219 requested_subdomain: subdomain,
220 };
221 let msg = serde_json::to_string(&hello)?;
222 ws.send(Message::Text(msg.into())).await?;
223
224 while let Some(frame) = ws.next().await {
226 let frame = frame.context("WebSocket error during handshake")?;
227 match frame {
228 Message::Text(text) => {
229 let server_msg: ServerMessage = serde_json::from_str(&text)?;
230 match server_msg {
231 ServerMessage::Assigned { url, subdomain } => {
232 info!(url = %url, subdomain = %subdomain, "tunnel assigned");
233 return Ok((url, ws));
234 }
235 ServerMessage::Error { message } => {
236 anyhow::bail!("server rejected tunnel: {message}");
237 }
238 _ => continue,
239 }
240 }
241 Message::Ping(_) => continue,
242 Message::Close(_) => anyhow::bail!("server closed connection during handshake"),
243 _ => continue,
244 }
245 }
246 anyhow::bail!("WebSocket closed before handshake completed")
247}
248
249async fn tunnel_loop(
252 ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
253 local_addr: SocketAddr,
254 mut shutdown_rx: watch::Receiver<bool>,
255) -> Result<()> {
256 let (ws_tx, mut ws_rx) = ws.split();
257 let ws_tx = Arc::new(Mutex::new(ws_tx));
258
259 loop {
260 tokio::select! {
261 _ = shutdown_rx.changed() => {
262 info!("tunnel shutting down");
263 let mut tx = ws_tx.lock().await;
264 let _ = tx.close().await;
265 return Ok(());
266 }
267 frame = ws_rx.next() => {
268 let Some(frame) = frame else {
269 warn!("tunnel WebSocket closed by server");
270 return Ok(());
271 };
272 let frame = frame?;
273 match frame {
274 Message::Text(text) => {
275 let server_msg: ServerMessage = serde_json::from_str(&text)?;
276 match server_msg {
277 ServerMessage::NewConnection { stream_id } => {
278 info!(%stream_id, "new visitor connection");
279 }
280 ServerMessage::Heartbeat => {
281 let pong = serde_json::to_string(&ClientMessage::Heartbeat)?;
282 let mut tx = ws_tx.lock().await;
283 let _ = tx.send(Message::Text(pong.into())).await;
284 }
285 ServerMessage::Error { message } => {
286 error!(%message, "server error");
287 }
288 _ => {}
289 }
290 }
291 Message::Binary(data) => {
292 let ws_tx = ws_tx.clone();
293 let local = local_addr;
294 tokio::spawn(async move {
295 handle_binary_frame(data.to_vec(), local, ws_tx).await;
296 });
297 }
298 Message::Ping(data) => {
299 let mut tx = ws_tx.lock().await;
300 let _ = tx.send(Message::Pong(data)).await;
301 }
302 Message::Close(_) => {
303 info!("server closed tunnel");
304 return Ok(());
305 }
306 _ => {}
307 }
308 }
309 }
310 }
311}
312
313async fn handle_binary_frame(data: Vec<u8>, local_addr: SocketAddr, ws_tx: Arc<Mutex<WsSink>>) {
315 let (stream_id, frame) = match decode_frame(&data) {
316 Ok(f) => f,
317 Err(e) => {
318 warn!(error = %e, "failed to decode binary frame");
319 return;
320 }
321 };
322
323 let TunnelFrame::Request(request) = frame else {
324 warn!(%stream_id, "expected request frame, got something else");
325 return;
326 };
327
328 let response_frame = match proxy_to_local(local_addr, &request).await {
330 Ok(resp) => TunnelFrame::Response(resp),
331 Err(e) => {
332 warn!(%stream_id, error = %e, "local proxy failed");
333 TunnelFrame::Error(TunnelError {
334 message: e.to_string(),
335 })
336 }
337 };
338
339 let binary = encode(stream_id, &response_frame);
341 let mut tx = ws_tx.lock().await;
342 if let Err(e) = tx.send(Message::Binary(binary.into())).await {
343 warn!(%stream_id, error = %e, "failed to send response frame");
344 }
345}
346
347async fn proxy_to_local(local_addr: SocketAddr, request: &TunnelRequest) -> Result<TunnelResponse> {
349 let stream = TcpStream::connect(local_addr)
350 .await
351 .context("failed to connect to local service")?;
352
353 let io = TokioIo::new(stream);
354
355 let (mut sender, conn) = http1::Builder::new()
356 .handshake::<_, Full<Bytes>>(io)
357 .await
358 .context("HTTP handshake with local service failed")?;
359
360 tokio::spawn(async move {
362 if let Err(e) = conn.await {
363 warn!(error = %e, "local HTTP connection error");
364 }
365 });
366
367 let method: hyper::Method = request.method.parse().context("invalid HTTP method")?;
369
370 let mut builder = Request::builder().method(method).uri(&request.uri);
371
372 for (name, value) in &request.headers {
373 builder = builder.header(name.as_str(), value.as_slice());
374 }
375
376 let body = if request.body.is_empty() {
377 Full::new(Bytes::new())
378 } else {
379 Full::new(Bytes::from(request.body.clone()))
380 };
381
382 let hyper_req = builder.body(body).context("failed to build request")?;
383
384 let resp: Response<Incoming> = sender
386 .send_request(hyper_req)
387 .await
388 .context("local service request failed")?;
389
390 let status = resp.status().as_u16();
391 let headers: Vec<(String, Vec<u8>)> = resp
392 .headers()
393 .iter()
394 .map(|(name, value)| (name.to_string(), value.as_bytes().to_vec()))
395 .collect();
396
397 let body = http_body_util::BodyExt::collect(resp.into_body())
398 .await
399 .context("failed to read local response body")?
400 .to_bytes()
401 .to_vec();
402
403 Ok(TunnelResponse {
404 status,
405 headers,
406 body,
407 })
408}