pocket-relay-client-shared 0.2.1

Shared logic for pocket relay client variants
Documentation
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
//! API logic for HTTP requests that are sent to the Pocket Relay server

use crate::{servers::HTTP_PORT, MIN_SERVER_VERSION};
use hyper::{
    header::{self, HeaderName, HeaderValue},
    Body, HeaderMap, Response,
};
use log::error;
use reqwest::{Client, Identity, Upgraded};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::{path::Path, str::FromStr};
use thiserror::Error;
use url::Url;

/// Endpoint used for requesting the server details
pub const DETAILS_ENDPOINT: &str = "api/server";
/// Endpoint used to publish telemetry events
pub const TELEMETRY_ENDPOINT: &str = "api/server/telemetry";
/// Endpoint for upgrading the server connection
pub const UPGRADE_ENDPOINT: &str = "api/server/upgrade";
/// Endpoint for creating a connection tunnel
pub const TUNNEL_ENDPOINT: &str = "api/server/tunnel";

/// Server identifier for validation
pub const SERVER_IDENT: &str = "POCKET_RELAY_SERVER";

/// Client user agent created from the name and version
pub const USER_AGENT: &str = concat!("PocketRelayClient/v", env!("CARGO_PKG_VERSION"));

// Headers used by the client
mod headers {
    /// Header used for association tokens
    pub const ASSOCIATION: &str = "x-association";

    /// Legacy header used to derive the server scheme (Exists only for backwards compatibility)
    pub const LEGACY_SCHEME: &str = "x-pocket-relay-scheme";
    /// Legacy header used to derive the server host (Exists only for backwards compatibility)
    pub const LEGACY_HOST: &str = "x-pocket-relay-host";
    /// Legacy header used to derive the server port (Exists only for backwards compatibility)
    pub const LEGACY_PORT: &str = "x-pocket-relay-port";
    /// Legacy header telling the server to use local http routing
    /// (Existing only for backwards compat, this is the default behavior for newer versions)
    pub const LEGACY_LOCAL_HTTP: &str = "x-pocket-relay-local-http";
}

/// Creates a new HTTP client to use, will use the client identity
/// if one is provided
///
/// ## Arguments
/// * `identity` - Optional identity for the client to use
pub fn create_http_client(identity: Option<Identity>) -> Result<Client, reqwest::Error> {
    let mut builder = Client::builder().user_agent(USER_AGENT);

    if let Some(identity) = identity {
        builder = builder.identity(identity);
    }

    builder.build()
}

/// Errors that can occur when loading the client identity
#[derive(Debug, Error)]
pub enum ClientIdentityError {
    /// Failed to read the identity file
    #[error("Failed to read identity: {0}")]
    Read(#[from] std::io::Error),
    /// Failed to create the identity
    #[error("Failed to create identity: {0}")]
    Create(#[from] reqwest::Error),
}

/// Attempts to read a client identity from the provided file path,
/// the file must be a .p12 / .pfx (PKCS12) format containing a
/// certificate and private key with a blank password
///
/// ## Arguments
/// * `path` - The path to read the identity from
pub fn read_client_identity(path: &Path) -> Result<Identity, ClientIdentityError> {
    // Read the identity file bytes
    let bytes = std::fs::read(path).map_err(ClientIdentityError::Read)?;

    // Parse the identity from the file bytes
    Identity::from_pkcs12_der(&bytes, "").map_err(ClientIdentityError::Create)
}

/// Details provided by the server. These are the only fields
/// that we need the rest are ignored by this client.
#[derive(Deserialize)]
struct ServerDetails {
    /// The Pocket Relay version of the server
    version: Version,
    /// Server identifier checked to ensure its a proper server
    #[serde(default)]
    ident: Option<String>,
    /// Association token if the server supports providing one
    association: Option<String>,
}

/// Data from completing a lookup contains the resolved address
/// from the connection to the server as well as the server
/// version obtained from the server
#[derive(Debug, Clone)]
pub struct LookupData {
    /// Server url
    pub url: Url,
    /// The server version
    pub version: Version,
    /// Association token if the server supports providing one
    pub association: Option<String>,
}

/// Errors that can occur while looking up a server
#[derive(Debug, Error)]
pub enum LookupError {
    /// The server url was invalid
    #[error("Invalid Connection URL: {0}")]
    InvalidHostTarget(#[from] url::ParseError),
    /// The server connection failed
    #[error("Failed to connect to server: {0}")]
    ConnectionFailed(reqwest::Error),
    /// The server gave an invalid response likely not a PR server
    #[error("Server replied with error response: {0}")]
    ErrorResponse(reqwest::Error),
    /// The server gave an invalid response likely not a PR server
    #[error("Invalid server response: {0}")]
    InvalidResponse(reqwest::Error),
    /// Server wasn't a valid pocket relay server
    #[error("Server identifier was incorrect (Not a PocketRelay server?)")]
    NotPocketRelay,
    /// Server version is too old
    #[error("Server version is too outdated ({0}) this client requires servers of version {1} or greater")]
    ServerOutdated(Version, Version),
}

/// Attempts to lookup a server at the provided url to see if
/// its a Pocket Relay server
///
/// ## Arguments
/// * `http_client` - The HTTP client to connect with
/// * `base_url`    - The server base URL (Connection URL)
pub async fn lookup_server(
    http_client: reqwest::Client,
    host: String,
) -> Result<LookupData, LookupError> {
    let mut url = String::new();

    // Whether a scheme was inferred
    let mut inferred_scheme = false;

    // Fill in missing scheme portion
    if !host.starts_with("http://") && !host.starts_with("https://") {
        url.push_str("http://");

        inferred_scheme = true;
    }

    url.push_str(&host);

    // Ensure theres a trailing slash (URL path will be interpreted incorrectly without)
    if !url.ends_with('/') {
        url.push('/');
    }

    let mut url = Url::from_str(&url)?;

    // Update scheme to be https if the 443 port was specified and the scheme was inferred as http://
    if url.port().is_some_and(|port| port == 443) && inferred_scheme {
        let _ = url.set_scheme("https");
    }

    let info_url = url
        .join(DETAILS_ENDPOINT)
        .expect("Failed to create server details URL");

    // Send the HTTP request and get its response
    let response = http_client
        .get(info_url)
        .header(header::ACCEPT, "application/json")
        .send()
        .await
        .map_err(LookupError::ConnectionFailed)?;

    // Debug printing of response details for debug builds
    #[cfg(debug_assertions)]
    {
        use log::debug;

        debug!("Response Status: {}", response.status());
        debug!("HTTP Version: {:?}", response.version());
        debug!("Content Length: {:?}", response.content_length());
        debug!("HTTP Headers: {:?}", response.headers());
    }

    // Ensure the response wasn't a non 200 response
    let response = response
        .error_for_status()
        .map_err(LookupError::ErrorResponse)?;

    // Parse the JSON serialized server details
    let details = response
        .json::<ServerDetails>()
        .await
        .map_err(LookupError::InvalidResponse)?;

    // Handle invalid server ident
    if details.ident.is_none() || details.ident.is_some_and(|value| value != SERVER_IDENT) {
        return Err(LookupError::NotPocketRelay);
    }

    // Ensure the server is a supported version
    if details.version < MIN_SERVER_VERSION {
        return Err(LookupError::ServerOutdated(
            details.version,
            MIN_SERVER_VERSION,
        ));
    }

    // Debug logging association acquire
    #[cfg(debug_assertions)]
    {
        use log::debug;
        if let Some(association) = &details.association {
            debug!("Acquired association token: {}", association);
        }
    }

    Ok(LookupData {
        url,
        version: details.version,
        association: details.association,
    })
}

/// Errors that could occur when creating a server stream
#[derive(Debug, Error)]
pub enum ServerStreamError {
    /// Initial HTTP request failure
    #[error("Request failed: {0}")]
    RequestFailed(reqwest::Error),
    /// Server responded with an error message
    #[error("Server error response: {0}")]
    ServerError(reqwest::Error),
    /// Upgrading the connection failed
    #[error("Upgrade failed: {0}")]
    UpgradeFailure(reqwest::Error),
}

/// Creates a BlazeSDK upgraded stream using HTTP upgrades
/// with the Pocket Relay server
///
/// ## Arguments
/// * `http_client` - The HTTP client to connect with
/// * `base_url`    - The server base URL (Connection URL)
/// * `association` - Optional client association token
pub async fn create_server_stream(
    http_client: &reqwest::Client,
    base_url: &Url,
    association: Option<&String>,
) -> Result<Upgraded, ServerStreamError> {
    // Create the upgrade endpoint URL
    let endpoint_url: Url = base_url
        .join(UPGRADE_ENDPOINT)
        .expect("Failed to create upgrade endpoint");

    // Headers to provide when upgrading
    let mut headers: HeaderMap<HeaderValue> = [
        (header::CONNECTION, HeaderValue::from_static("Upgrade")),
        (header::UPGRADE, HeaderValue::from_static("blaze")),
        // Headers for legacy compatibility
        (
            HeaderName::from_static(headers::LEGACY_SCHEME),
            HeaderValue::from_static("http"),
        ),
        (
            HeaderName::from_static(headers::LEGACY_HOST),
            HeaderValue::from_static("127.0.0.1"),
        ),
        (
            HeaderName::from_static(headers::LEGACY_PORT),
            HeaderValue::from(HTTP_PORT),
        ),
        (
            HeaderName::from_static(headers::LEGACY_LOCAL_HTTP),
            HeaderValue::from_static("true"),
        ),
    ]
    .into_iter()
    .collect();

    // Include association token
    if let Some(association) = association {
        headers.insert(
            HeaderName::from_static(headers::ASSOCIATION),
            HeaderValue::from_str(association).expect("Invalid association token"),
        );
    }

    // Send the HTTP request and get its response
    let response = http_client
        .get(endpoint_url)
        .headers(headers)
        .send()
        .await
        .map_err(ServerStreamError::RequestFailed)?;

    // Handle server error responses
    let response = response
        .error_for_status()
        .map_err(ServerStreamError::ServerError)?;

    // Upgrade the connection
    response
        .upgrade()
        .await
        .map_err(ServerStreamError::UpgradeFailure)
}

/// Key value pair message for telemetry events
#[derive(Serialize)]
pub struct TelemetryEvent {
    /// The telemetry values
    pub values: Vec<(String, String)>,
}

/// Publishes a new telemetry event to the Pocket Relay server
///
/// ## Arguments
/// * `http_client` - The HTTP client to connect with
/// * `base_url`    - The server base URL (Connection URL)
/// * `event`       - The event to publish
pub async fn publish_telemetry_event(
    http_client: &reqwest::Client,
    base_url: &Url,
    event: TelemetryEvent,
) -> Result<(), reqwest::Error> {
    // Create the telemetry endpoint URL
    let endpoint_url: Url = base_url
        .join(TELEMETRY_ENDPOINT)
        .expect("Failed to create telemetry endpoint");

    // Send the HTTP request and get its response
    let response = http_client.post(endpoint_url).json(&event).send().await?;

    // Handle server error responses
    let _ = response.error_for_status()?;

    Ok(())
}

/// Errors that could occur in the proxy process
#[derive(Debug, Error)]
pub enum ProxyError {
    /// Initial HTTP request failure
    #[error("Request failed: {0}")]
    RequestFailed(reqwest::Error),
    /// Failed to read the response body bytes
    #[error("Request failed: {0}")]
    BodyFailed(reqwest::Error),
}

/// Proxies an HTTP request to the Pocket Relay server returning a
/// hyper response that can be served
///
/// ## Arguments
/// * `http_client` - The HTTP client to connect with
/// * `url`         - The server URL to request
pub async fn proxy_http_request(
    http_client: &reqwest::Client,
    url: Url,
) -> Result<Response<Body>, ProxyError> {
    // Send the HTTP request and get its response
    let response = http_client
        .get(url)
        .send()
        .await
        .map_err(ProxyError::RequestFailed)?;

    // Extract response status and headers before its consumed to load the body
    let status = response.status();
    let headers = response.headers().clone();

    // Read the response body bytes
    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));
    *response.status_mut() = status;
    *response.headers_mut() = headers;

    Ok(response)
}

/// Creates a networking tunnel for game packets
///
/// ## Arguments
/// * `http_client` - The HTTP client to connect with
/// * `base_url`    - The server base URL (Connection URL)
/// * `association` - Association token
pub async fn create_server_tunnel(
    http_client: &reqwest::Client,
    base_url: &Url,
    association: &str,
) -> Result<Upgraded, ServerStreamError> {
    // Create the upgrade endpoint URL
    let endpoint_url: Url = base_url
        .join(TUNNEL_ENDPOINT)
        .expect("Failed to create tunnel endpoint");

    // Headers to provide when upgrading
    let mut headers: HeaderMap<HeaderValue> = [
        (header::CONNECTION, HeaderValue::from_static("Upgrade")),
        (header::UPGRADE, HeaderValue::from_static("tunnel")),
    ]
    .into_iter()
    .collect();

    // Include association token
    headers.insert(
        HeaderName::from_static(headers::ASSOCIATION),
        HeaderValue::from_str(association).expect("Invalid association token"),
    );

    // Send the HTTP request and get its response
    let response = http_client
        .get(endpoint_url)
        .headers(headers)
        .send()
        .await
        .map_err(ServerStreamError::RequestFailed)?;

    // Handle server error responses
    let response = response
        .error_for_status()
        .map_err(ServerStreamError::ServerError)?;

    // Upgrade the connection
    response
        .upgrade()
        .await
        .map_err(ServerStreamError::UpgradeFailure)
}