Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pocket-relay-client-shared"
version = "0.3.0"
version = "1.0.0"
edition = "2021"
description = "Shared logic for pocket relay client variants"
authors = ["Jacobtread <jacobtread@gmail.com>"]
Expand All @@ -17,9 +17,11 @@ pocket-relay-udp-tunnel = { version = "0" }
log = "0.4"

# HTTP client (native-tls is required for client auth)
reqwest = { version = "0.11", default-features = false, features = [
"json",
"native-tls",
reqwest = { version = "0.13", default-features = false, features = [
"charset",
"json",
"native-tls",
"http2",
] }

# Serialization
Expand All @@ -29,19 +31,21 @@ serde = { version = "1", features = ["derive"] }
blaze-ssl-async = "0.4"

# Library for obtaining the local IP address of the device
local-ip-address = "0.5"
local-ip-address = "0.6"

# Semantic versioning
# Semantic versioning
semver = { version = "1.0", features = ["serde"] }

# Low level HTTP access
hyper = { version = "0.14", features = ["server", "http1", "tcp", "runtime"] }
hyper = { version = "1", features = ["full"] }
http-body-util = "0.1"
hyper-util = { version = "0.1", features = ["full"] }

# URL parsing and manipulation
url = "2.4.1"

# TDF reading and writing
tdf = "0.1"
tdf = "0.4"

# Byte buffers
bytes = "1.4.0"
Expand All @@ -54,7 +58,7 @@ tokio-util = { version = "0.7", features = ["codec"] }
futures = "0.3"

# Error derive macros
thiserror = "1"
thiserror = "2"

# Locking primitives
parking_lot = "0.12.1"
parking_lot = "0.13"
9 changes: 5 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
//! API logic for HTTP requests that are sent to the Pocket Relay server

use crate::{servers::HTTP_PORT, MIN_SERVER_VERSION};
use bytes::Bytes;
use http_body_util::Full;
use hyper::{
header::{self, HeaderName, HeaderValue},
Body, HeaderMap, Response,
HeaderMap, Response,
};
use log::error;
use reqwest::{Client, Identity, Upgraded};
use semver::Version;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -373,7 +374,7 @@ pub enum ProxyError {
pub async fn proxy_http_request(
http_client: &reqwest::Client,
url: Url,
) -> Result<Response<Body>, ProxyError> {
) -> Result<Response<Full<Bytes>>, ProxyError> {
// Send the HTTP request and get its response
let response = http_client
.get(url)
Expand All @@ -389,7 +390,7 @@ pub async fn proxy_http_request(
let body: bytes::Bytes = response.bytes().await.map_err(ProxyError::BodyFailed)?;

// Create new response from the proxy response
let mut response = Response::new(Body::from(body));
let mut response = Response::new(Full::new(body));
*response.status_mut() = status;
*response.headers_mut() = headers;

Expand Down
22 changes: 22 additions & 0 deletions src/events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Event types for any events that servers may need to emit

/// Events that tunnel servers can emit
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TunnelEvent {
/// Creating the tunnel server
Creating,

/// Performing a handshake to try and connect
/// (UDP tunnel only, the HTTP tunnel does not have a handshake to track it goes from creating -> connected)
Handshaking,

/// Currently connected
Connected,

/// Attempting to reconnect
RetryConnect,

/// Error occurred while connecting and unable to connect, reached limit
/// of connection retries
Error,
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub use url::Url;

pub mod api;
pub mod ctx;
pub mod events;
pub mod fire;
pub mod servers;
pub mod update;
Expand Down
38 changes: 22 additions & 16 deletions src/servers/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@

use super::HTTP_PORT;
use crate::{api::proxy_http_request, ctx::ClientContext};
use bytes::Bytes;
use http_body_util::Full;
use hyper::{
http::uri::PathAndQuery,
service::{make_service_fn, service_fn},
Body, Request, Response, Server, StatusCode,
body::Incoming, http::uri::PathAndQuery, server::conn::http1, service::service_fn, Request,
Response, StatusCode,
};
use hyper_util::rt::TokioIo;
use log::error;
use std::{
convert::Infallible,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::Arc,
};
use tokio::net::TcpListener;

/// Starts the HTTP proxy server
///
Expand All @@ -23,20 +26,23 @@ use std::{
pub async fn start_http_server(ctx: Arc<ClientContext>) -> std::io::Result<()> {
// Create the socket address the server will bind too
let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, HTTP_PORT));
let listener = TcpListener::bind(addr).await?;

// Create service that uses the `handle function`
let make_svc = make_service_fn(move |_conn| {
let ctx = ctx.clone();

async move {
// service_fn converts our function into a `Service`
Ok::<_, Infallible>(service_fn(move |request| handle(request, ctx.clone())))
}
});
loop {
let (stream, _) = listener.accept().await?;

let server = Server::bind(&addr).serve(make_svc);
let io = TokioIo::new(stream);
let ctx = ctx.clone();

server.await.map_err(std::io::Error::other)
tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(io, service_fn(move |request| handle(request, ctx.clone())))
.await
{
eprintln!("Error serving connection: {:?}", err);
}
});
}
}

/// Handles an HTTP request from the HTTP acting as a proxy
Expand All @@ -46,9 +52,9 @@ pub async fn start_http_server(ctx: Arc<ClientContext>) -> std::io::Result<()> {
/// * `request` - The HTTP request
/// * `ctx` - The client context
async fn handle(
request: Request<Body>,
request: Request<Incoming>,
ctx: Arc<ClientContext>,
) -> Result<Response<Body>, Infallible> {
) -> Result<Response<Full<Bytes>>, Infallible> {
let path_and_query = request
.uri()
// Extract the path and query portion of the url
Expand Down
51 changes: 35 additions & 16 deletions src/servers/tunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use self::codec::{TunnelCodec, TunnelMessage};
use crate::{
api::create_server_tunnel,
ctx::ClientContext,
events::TunnelEvent,
servers::{spawn_server_task, GAME_HOST_PORT, RANDOM_PORT, TUNNEL_HOST_PORT},
};
use bytes::Bytes;
Expand Down Expand Up @@ -41,7 +42,11 @@ static LOCAL_SEND_TARGET: SocketAddr =
///
/// ## Arguments
/// * `ctx` - The client context
pub async fn start_tunnel_server(ctx: Arc<ClientContext>) -> std::io::Result<()> {
/// * `event_tx` - Channel for sending tunnel events through
pub async fn start_tunnel_server(
ctx: Arc<ClientContext>,
event_tx: mpsc::UnboundedSender<TunnelEvent>,
) -> std::io::Result<()> {
let association = match Option::as_ref(&ctx.association) {
Some(value) => value,
// Don't try and tunnel without a token
Expand All @@ -56,24 +61,27 @@ pub async fn start_tunnel_server(ctx: Arc<ClientContext>) -> std::io::Result<()>
// Looping to attempt reconnecting if lost
while attempt_errors < MAX_ERROR_ATTEMPTS {
// Create the tunnel (Future will end if tunnel stopped)
let reconnect_time = if let Err(err) = create_tunnel(ctx.clone(), association).await {
error!("Failed to create tunnel: {}", err);
let reconnect_time =
if let Err(err) = create_tunnel(ctx.clone(), association, &event_tx).await {
error!("Failed to create tunnel: {}", err);

// Set last error
last_error = Some(err);
// Set last error
last_error = Some(err);

// Increase error attempts
attempt_errors += 1;
// Increase error attempts
attempt_errors += 1;

// Error should be delayed by the number of errors already hit
Duration::from_millis(1000 * attempt_errors as u64)
} else {
// Reset error attempts
attempt_errors = 0;
// Error should be delayed by the number of errors already hit
Duration::from_millis(1000 * attempt_errors as u64)
} else {
// Reset error attempts
attempt_errors = 0;

// Non errored reconnect can be quick
Duration::from_millis(1000)
};
// Non errored reconnect can be quick
Duration::from_millis(1000)
};

_ = event_tx.send(TunnelEvent::RetryConnect);

debug!(
"Next tunnel create attempt in: {}s",
Expand All @@ -84,6 +92,8 @@ pub async fn start_tunnel_server(ctx: Arc<ClientContext>) -> std::io::Result<()>
tokio::time::sleep(reconnect_time).await;
}

_ = event_tx.send(TunnelEvent::Error);

Err(last_error.unwrap_or(std::io::Error::other("Reached error connect limit")))
}

Expand All @@ -92,7 +102,15 @@ pub async fn start_tunnel_server(ctx: Arc<ClientContext>) -> std::io::Result<()>
/// ## Arguments
/// * `ctx` - The client context
/// * `association` - The client association token
async fn create_tunnel(ctx: Arc<ClientContext>, association: &str) -> std::io::Result<()> {
/// * `event_tx` - Channel for sending tunnel events through
async fn create_tunnel(
ctx: Arc<ClientContext>,
association: &str,
event_tx: &mpsc::UnboundedSender<TunnelEvent>,
) -> std::io::Result<()> {
// No hand
_ = event_tx.send(TunnelEvent::Creating);

// Create the tunnel with the server
let io = create_server_tunnel(&ctx.http_client, &ctx.base_url, association)
.await
Expand All @@ -101,6 +119,7 @@ async fn create_tunnel(ctx: Arc<ClientContext>, association: &str) -> std::io::R
// Wrap the error into an [`std::io::Error`]
.map_err(std::io::Error::other)?;
debug!("Created server tunnel");
_ = event_tx.send(TunnelEvent::Connected);

// Allocate the socket pool for the tunnel
let (tx, rx) = mpsc::unbounded_channel();
Expand Down
42 changes: 27 additions & 15 deletions src/servers/udp_tunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use crate::{
ctx::ClientContext,
events::TunnelEvent,
servers::{spawn_server_task, GAME_HOST_PORT, RANDOM_PORT, TUNNEL_HOST_PORT},
};
use log::{debug, error};
Expand Down Expand Up @@ -90,6 +91,7 @@ pub enum UdpTunnelError {
pub async fn start_udp_tunnel_server(
ctx: Arc<ClientContext>,
tunnel_port: u16,
event_tx: mpsc::UnboundedSender<TunnelEvent>,
) -> std::io::Result<()> {
let host = match ctx.base_url.host() {
Some(value) => value.to_string(),
Expand All @@ -111,25 +113,27 @@ pub async fn start_udp_tunnel_server(
// Looping to attempt reconnecting if lost
while attempt_errors < MAX_ERROR_ATTEMPTS {
// Create the tunnel (Future will end if tunnel stopped)
let reconnect_time = if let Err(err) = create_tunnel(&host, tunnel_port, association).await
{
error!("Failed to create tunnel: {}", err);
let reconnect_time =
if let Err(err) = create_tunnel(&host, tunnel_port, association, &event_tx).await {
error!("Failed to create tunnel: {}", err);

// Set last error
last_error = Some(err);
// Set last error
last_error = Some(err);

// Increase error attempts
attempt_errors += 1;
// Increase error attempts
attempt_errors += 1;

// Error should be delayed by the number of errors already hit
Duration::from_millis(1000 * attempt_errors as u64)
} else {
// Reset error attempts
attempt_errors = 0;
// Error should be delayed by the number of errors already hit
Duration::from_millis(1000 * attempt_errors as u64)
} else {
// Reset error attempts
attempt_errors = 0;

// Non errored reconnect can be quick
Duration::from_millis(1000)
};
// Non errored reconnect can be quick
Duration::from_millis(1000)
};

_ = event_tx.send(TunnelEvent::RetryConnect);

debug!(
"Next tunnel create attempt in: {}s",
Expand All @@ -140,6 +144,8 @@ pub async fn start_udp_tunnel_server(
tokio::time::sleep(reconnect_time).await;
}

_ = event_tx.send(TunnelEvent::Error);

Err(last_error
.map(std::io::Error::other)
.unwrap_or(std::io::Error::other("Reached error connect limit")))
Expand All @@ -155,12 +161,17 @@ async fn create_tunnel(
host: &str,
tunnel_port: u16,
association: &str,
event_tx: &mpsc::UnboundedSender<TunnelEvent>,
) -> Result<(), UdpTunnelError> {
_ = event_tx.send(TunnelEvent::Creating);

// Bind a local udp socket
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
.await
.map_err(UdpTunnelError::Bind)?;

_ = event_tx.send(TunnelEvent::Handshaking);

// Map connection to remote tunnel server
socket
.connect((host, tunnel_port))
Expand All @@ -170,6 +181,7 @@ async fn create_tunnel(
debug!("initiating tunnel: {}:{}", host, tunnel_port);

let tunnel_id = attempt_tunnel_handshake(&socket, association).await?;
_ = event_tx.send(TunnelEvent::Connected);

debug!("created server tunnel: {}", tunnel_id);

Expand Down
Loading