Skip to content

Commit 10771b3

Browse files
committed
v1.1
1 parent 26dd6b8 commit 10771b3

4 files changed

Lines changed: 86 additions & 19 deletions

File tree

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ lto = "fat"
88
codegen-units = 1
99
strip = "symbols"
1010

11-
[profile.release.package.proxy]
11+
[profile.release.package.spacegate-proxy]
1212
opt-level = 3

example/Dockerfile

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
FROM debian:bullseye-slim AS stage
2+
WORKDIR /dl
3+
RUN cd /dl && apt update && \
4+
apt install wget -y && \
5+
wget https://github.com/suirad/spacegate/releases/download/v1.1/spacegate-proxy-x86_64-linux-musl.tar.gz && \
6+
tar xf spacegate-proxy-x86_64-linux-musl.tar.gz
7+
RUN ls
8+
9+
FROM gcr.io/distroless/static AS runner
10+
COPY --from=stage /dl/spacegate-proxy /bin/spacegate-proxy
11+
CMD ["/bin/spacegate-proxy"]

example/docker-compose.yml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
services:
2+
db:
3+
networks: [stdb]
4+
image: clockworklabs/spacetime:v1.1.0
5+
command: start
6+
7+
proxy:
8+
networks: [stdb]
9+
build:
10+
dockerfile: Dockerfile
11+
command: /bin/spacegate-proxy -t db:3000
12+
13+
networks:
14+
stdb:
15+

proxy/src/main.rs

Lines changed: 59 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use tokio_rustls::{
2323
},
2424
TlsConnector,
2525
};
26-
use tracing::{error, info};
26+
use tracing::{debug, error, info};
2727
use tracing_subscriber::{self, EnvFilter};
2828

2929
#[derive(Debug, Parser)]
@@ -55,12 +55,15 @@ struct Args {
5555

5656
#[arg(long, hide = true, default_value_t = false)]
5757
fly: bool,
58+
59+
#[arg(long, hide = true, default_value_t = false)]
60+
debug: bool,
5861
}
5962

6063
#[tokio::main]
6164
async fn main() -> Result<()> {
6265
tracing_subscriber::fmt()
63-
.with_env_filter(EnvFilter::new("spacegate_proxy=info"))
66+
.with_env_filter(EnvFilter::new("spacegate_proxy=debug"))
6467
.init();
6568

6669
let mut args = Args::parse();
@@ -74,6 +77,8 @@ async fn main() -> Result<()> {
7477
start_server_local(&mut args).await?
7578
};
7679

80+
let args = Arc::new(args);
81+
7782
info!(
7883
"Successfully Initialized\nNode info: {:#?}",
7984
endpoint.node_addr().await?
@@ -96,8 +101,8 @@ async fn main() -> Result<()> {
96101
continue;
97102
};
98103

99-
let targ = args.target_uri.clone();
100-
tokio::spawn(async move { handle_conn(conn, targ).await });
104+
let cargs = args.clone();
105+
tokio::spawn(async move { handle_conn(conn, cargs).await });
101106
}
102107
}
103108

@@ -167,7 +172,7 @@ async fn start_server_fly(args: &mut Args) -> Result<Endpoint> {
167172
_start_server(args, "maincloud", Some(key)).await
168173
}
169174

170-
async fn handle_conn(conn: Connection, target: String) -> Result<()> {
175+
async fn handle_conn(conn: Connection, args: Arc<Args>) -> Result<()> {
171176
info!("New connection ID: {}", conn.stable_id());
172177

173178
loop {
@@ -179,8 +184,8 @@ async fn handle_conn(conn: Connection, target: String) -> Result<()> {
179184
let desc = format!("{}:{}", conn.stable_id(), recv.id().index());
180185
info!("Starting proxy for {}", &desc);
181186

182-
let targ = target.clone();
183-
tokio::spawn(async move { proxy_stream(send, recv, targ, desc).await });
187+
let cargs = args.clone();
188+
tokio::spawn(async move { proxy_stream(send, recv, cargs, desc).await });
184189
}
185190

186191
Ok(())
@@ -189,14 +194,15 @@ async fn handle_conn(conn: Connection, target: String) -> Result<()> {
189194
async fn proxy_stream(
190195
mut send: SendStream,
191196
mut recv: RecvStream,
192-
target: String,
197+
args: Arc<Args>,
193198
desc: String,
194199
) -> Result<()> {
195-
let stream = TcpStream::connect(&target)
200+
let stream = TcpStream::connect(&args.target_uri)
196201
.await
197202
.expect("Failed to connect to target server {target}");
198203

199-
let (host, port): (String, u16) = target
204+
let (host, port): (String, u16) = args
205+
.target_uri
200206
.split_once(':')
201207
.map(|(h, p)| (h.to_owned(), p.parse().unwrap()))
202208
.unwrap();
@@ -219,22 +225,28 @@ async fn proxy_stream(
219225
.await?;
220226
let (mut trecv, mut tsend) = tokio::io::split(tls);
221227

222-
if let Err(e) = rewrite_host_header(&mut recv, &mut tsend, &host).await {
228+
if let Err(e) = rewrite_host_header(&mut recv, &mut tsend, &host, args).await {
223229
panic!("Error parsing host header out of request: {e}");
224230
}
231+
225232
tokio::select! {
226233
biased;
227234
_ = tokio::io::copy(&mut recv, &mut tsend) => {},
228235
_ = tokio::io::copy(&mut trecv, &mut send) => {},
229236
}
230237
}
231238
_ => {
232-
let conn = TcpStream::connect(&target).await?;
239+
let conn = TcpStream::connect(&args.target_uri).await?;
233240
let (mut trecv, mut tsend) = tokio::io::split(conn);
234241

235-
if let Err(e) = rewrite_host_header(&mut recv, &mut tsend, &host).await {
236-
panic!("Error parsing host header out of request: {e}");
242+
if args.debug {
243+
if let Err(e) =
244+
rewrite_host_header(&mut recv, &mut tsend, &args.target_uri.clone(), args).await
245+
{
246+
panic!("Error parsing host header out of request: {e}");
247+
}
237248
}
249+
238250
tokio::select! {
239251
biased;
240252
_ = tokio::io::copy(&mut recv, &mut tsend) => {},
@@ -251,8 +263,10 @@ async fn rewrite_host_header<T: tokio::io::AsyncWrite>(
251263
recv: &mut RecvStream,
252264
prox_send: &mut WriteHalf<T>,
253265
new_host: &str,
266+
args: Arc<Args>,
254267
) -> Result<()> {
255-
let mut buf = [0u8; 200];
268+
// buf size is arbitrary, just large enough to capture head header during module publish
269+
let mut buf = [0u8; 640];
256270

257271
let len = recv.read(&mut buf).await?.unwrap_or(0);
258272

@@ -264,9 +278,19 @@ async fn rewrite_host_header<T: tokio::io::AsyncWrite>(
264278
"Host: ".as_bytes(),
265279
new_host.as_bytes(),
266280
"\n".as_bytes(),
267-
post_host.split_once('\n').unwrap().1.as_bytes(),
281+
post_host.split_once('\n').unwrap_or(("", "")).1.as_bytes(),
282+
if data.len() < buf.len() {
283+
"\n".as_bytes()
284+
} else {
285+
"".as_bytes()
286+
},
268287
];
269288

289+
if args.debug {
290+
let msg = String::from_iter(chunks.iter().map(|c| std::str::from_utf8(c).unwrap()));
291+
debug!("Patched headers from:\n'{data:#}'\nto\n'{msg:#}'");
292+
}
293+
270294
for chunk in chunks {
271295
prox_send.write_all(chunk).await?;
272296
}
@@ -276,14 +300,31 @@ async fn rewrite_host_header<T: tokio::io::AsyncWrite>(
276300
"host: ".as_bytes(),
277301
new_host.as_bytes(),
278302
"\n".as_bytes(),
279-
post_host.split_once('\n').unwrap().1.as_bytes(),
303+
post_host.split_once('\n').unwrap_or(("", "")).1.as_bytes(),
304+
if data.len() < buf.len() {
305+
"\n".as_bytes()
306+
} else {
307+
"".as_bytes()
308+
},
280309
];
281310

311+
if args.debug {
312+
let msg = String::from_iter(chunks.iter().map(|c| std::str::from_utf8(c).unwrap()));
313+
debug!("Patched headers from:\n'{data:#}'\nto\n'{msg:#}'");
314+
}
315+
282316
for chunk in chunks {
283317
prox_send.write_all(chunk).await?;
284318
}
285319
} else {
286-
prox_send.write_all(&buf[0..len]).await?;
320+
if args.debug {
321+
debug!(
322+
"Forwarding http connection without patching Host header:\n{:#}",
323+
&data
324+
);
325+
}
326+
327+
prox_send.write_all(&buf).await?;
287328
}
288329

289330
Ok(())

0 commit comments

Comments
 (0)