eggress-core 1.0.10

Core types, traits, and infrastructure for eggress proxy
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
use std::fmt;
use std::net::IpAddr;
use std::sync::Arc;

use tokio::io::{AsyncRead, AsyncWrite};

pub use capability::{
    classify_upstream_chain, CapabilityResult, TransportCapability, UpstreamCapabilities,
};

pub mod capability;
pub mod chain;
pub mod connector;
pub mod detect;
pub mod dispatch;
pub mod listener;
pub mod relay;
pub mod replay;

/// A unique identifier for a protocol handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProtocolId {
    Http,
    Socks4,
    Socks5,
    Shadowsocks,
    ShadowsocksR,
    Trojan,
    Http2,
    Http3,
    Quic,
    WebSocket,
    Raw,
    Echo,
    Reverse,
}

impl fmt::Display for ProtocolId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProtocolId::Http => write!(f, "http"),
            ProtocolId::Socks4 => write!(f, "socks4"),
            ProtocolId::Socks5 => write!(f, "socks5"),
            ProtocolId::Shadowsocks => write!(f, "shadowsocks"),
            ProtocolId::ShadowsocksR => write!(f, "ssr"),
            ProtocolId::Trojan => write!(f, "trojan"),
            ProtocolId::Http2 => write!(f, "h2"),
            ProtocolId::Http3 => write!(f, "h3"),
            ProtocolId::Quic => write!(f, "quic"),
            ProtocolId::WebSocket => write!(f, "websocket"),
            ProtocolId::Raw => write!(f, "raw"),
            ProtocolId::Echo => write!(f, "echo"),
            ProtocolId::Reverse => write!(f, "reverse"),
        }
    }
}

/// Failure to convert URI syntax into a dispatchable runtime protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ProtocolConversionError {
    /// The syntax concept has no listener/runtime role (e.g. SSH upstream-only).
    #[error("SSH is an upstream-only transport, not a listener protocol")]
    UpstreamOnlyTransport,
}

impl ProtocolId {
    /// Central typed conversion from URI syntax to runtime disposition.
    ///
    /// Exhaustive over [`eggress_uri::ProtocolSpec`]; unsupported and
    /// non-dispatchable variants fail explicitly instead of silent fallback:
    ///
    /// - `HttpOnly` is an upstream request adapter; listeners serve `Http`.
    /// - `Unix` is a transport concept; listeners serve it as `Raw` TCP
    ///   semantics with a unix-socket bind (see `ListenerUdpConfig`/unix listener).
    /// - `Ssh` is upstream-only and returns [`ProtocolConversionError::UpstreamOnlyTransport`].
    /// - `Echo` / `Reverse` are runtime-only: they have no `ProtocolSpec`
    ///   counterpart and never flow through this conversion.
    /// - `Raw` covers both `raw` and `tunnel` URI aliases (canonicalized in
    ///   `ProtocolSpec`), and `WebSocket` covers `ws`/`wss`.
    /// - `H3`/`Quic` map directly; feature gating (optional `quic` build)
    ///   stays in config compilation, not here.
    pub fn from_protocol_spec(
        spec: eggress_uri::ProtocolSpec,
    ) -> Result<Self, ProtocolConversionError> {
        use eggress_uri::ProtocolSpec as S;
        match spec {
            S::Http | S::HttpOnly => Ok(ProtocolId::Http),
            S::Socks4 => Ok(ProtocolId::Socks4),
            S::Socks5 => Ok(ProtocolId::Socks5),
            S::Shadowsocks => Ok(ProtocolId::Shadowsocks),
            S::ShadowsocksR => Ok(ProtocolId::ShadowsocksR),
            S::Trojan => Ok(ProtocolId::Trojan),
            S::Http2 => Ok(ProtocolId::Http2),
            S::Http3 => Ok(ProtocolId::Http3),
            S::Quic => Ok(ProtocolId::Quic),
            S::WebSocket => Ok(ProtocolId::WebSocket),
            S::Raw => Ok(ProtocolId::Raw),
            S::Unix => Ok(ProtocolId::Raw),
            S::Ssh => Err(ProtocolConversionError::UpstreamOnlyTransport),
        }
    }
}

/// A unique identifier for a listener.
pub type ListenerId = u64;

/// A unique identifier for an upstream proxy.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UpstreamId(Arc<str>);

impl serde::Serialize for UpstreamId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl UpstreamId {
    pub fn new(id: impl Into<Arc<str>>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for UpstreamId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for UpstreamId {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::new(s))
    }
}

/// The host of a target server, either an IP address or a domain name.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TargetHost {
    Ip(IpAddr),
    Domain(String),
}

impl fmt::Display for TargetHost {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TargetHost::Ip(ip) => write!(f, "{}", ip),
            TargetHost::Domain(domain) => write!(f, "{}", domain),
        }
    }
}

/// The address of a target server.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TargetAddr {
    pub host: TargetHost,
    pub port: u16,
}

impl fmt::Display for TargetAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.host {
            TargetHost::Ip(IpAddr::V6(_)) => write!(f, "[{}]:{}", self.host, self.port),
            _ => write!(f, "{}:{}", self.host, self.port),
        }
    }
}

impl std::str::FromStr for TargetAddr {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(rest) = s.strip_prefix('[') {
            let close = rest
                .find(']')
                .ok_or_else(|| format!("invalid target format: missing closing ']' in '{s}'"))?;
            let host_str = &rest[..close];
            let after = &rest[close + 1..];
            let port_str = after.strip_prefix(':').ok_or_else(|| {
                format!("invalid target format: missing ':port' after ']' in '{s}'")
            })?;
            let port: u16 = port_str
                .parse()
                .map_err(|e| format!("invalid port '{port_str}': {e}"))?;
            let ip: IpAddr = host_str
                .parse()
                .map_err(|e| format!("invalid IPv6 address '{host_str}': {e}"))?;
            Ok(TargetAddr {
                host: TargetHost::Ip(ip),
                port,
            })
        } else if s.matches(':').count() > 1 {
            Err(format!(
                "invalid target format: unbracketed IPv6 literal in '{s}' (use [addr]:port)"
            ))
        } else if let Some(idx) = s.rfind(':') {
            let host_part = &s[..idx];
            let port_part = &s[idx + 1..];
            let port: u16 = port_part
                .parse()
                .map_err(|e| format!("invalid port '{port_part}': {e}"))?;
            let host = if let Ok(ip) = host_part.parse::<IpAddr>() {
                TargetHost::Ip(ip)
            } else {
                TargetHost::Domain(host_part.to_string())
            };
            Ok(TargetAddr { host, port })
        } else {
            Err(format!("invalid target format: {s}"))
        }
    }
}

/// Client identity information.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientIdentity {
    Anonymous,
    Username(String),
    Opaque(String),
}

/// Context for a proxy session.
#[derive(Debug, Clone)]
pub struct SessionContext {
    pub session_id: u64,
    pub client_identity: ClientIdentity,
    pub target_addr: TargetAddr,
}

/// Action to take for a routed connection.
#[derive(Debug, Clone)]
pub enum RouteAction {
    Direct,
    Upstream(UpstreamId),
    Reject(RejectReason),
}

/// Reason for rejecting a connection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RejectReason {
    UnsupportedProtocol,
    AuthRequired,
    AccessDenied,
    Blocked,
    InternalError,
}

impl fmt::Display for RejectReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RejectReason::UnsupportedProtocol => write!(f, "unsupported protocol"),
            RejectReason::AuthRequired => write!(f, "authentication required"),
            RejectReason::AccessDenied => write!(f, "access denied"),
            RejectReason::Blocked => write!(f, "target address blocked"),
            RejectReason::InternalError => write!(f, "internal error"),
        }
    }
}

/// A trait that combines AsyncRead and AsyncWrite for bidirectional streams.
pub trait AsyncStream: AsyncRead + AsyncWrite + Send + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Unpin> AsyncStream for T {}

/// A type alias for a boxed async stream.
pub type BoxStream = Box<dyn AsyncStream>;

/// Error types for connection operations.
#[derive(Debug, thiserror::Error)]
pub enum ConnectError {
    #[error("connection refused")]
    ConnectionRefused,
    #[error("connection timed out")]
    Timeout,
    #[error("DNS resolution failed: {0}")]
    DnsResolution(String),
    #[error("TLS handshake failed: {0}")]
    TlsHandshake(String),
    #[error("reserved or private target IP: {0}")]
    ReservedTarget(std::net::IpAddr),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// Error types for protocol operations.
#[derive(Debug, thiserror::Error)]
pub enum ProtocolError {
    #[error("malformed message")]
    MalformedMessage,
    #[error("unsupported version")]
    UnsupportedVersion,
    #[error("method not supported")]
    MethodNotSupported,
    #[error("address type not supported")]
    AddressTypeNotSupported,
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// Error types for authentication operations.
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    #[error("invalid credentials")]
    InvalidCredentials,
    #[error("authentication method not supported")]
    MethodNotSupported,
    #[error("authentication required")]
    Required,
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// Error types for relay operations.
#[derive(Debug, thiserror::Error)]
pub enum RelayError {
    #[error("connection closed")]
    ConnectionClosed,
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_target_host_display() {
        let ip_host = TargetHost::Ip("127.0.0.1".parse().unwrap());
        assert_eq!(ip_host.to_string(), "127.0.0.1");

        let domain_host = TargetHost::Domain("example.com".to_string());
        assert_eq!(domain_host.to_string(), "example.com");
    }

    #[test]
    fn test_target_addr_display() {
        let addr = TargetAddr {
            host: TargetHost::Domain("example.com".to_string()),
            port: 8080,
        };
        assert_eq!(addr.to_string(), "example.com:8080");
    }

    #[test]
    fn test_reject_reason_display() {
        assert_eq!(
            RejectReason::UnsupportedProtocol.to_string(),
            "unsupported protocol"
        );
        assert_eq!(
            RejectReason::AuthRequired.to_string(),
            "authentication required"
        );
    }

    #[test]
    fn test_target_addr_from_str_bracketed_ipv6() {
        let addr: TargetAddr = "[::1]:443".parse().unwrap();
        assert_eq!(addr.host, TargetHost::Ip("::1".parse::<IpAddr>().unwrap()));
        assert_eq!(addr.port, 443);
    }

    #[test]
    fn test_target_addr_from_str_full_ipv6() {
        let addr: TargetAddr = "[2001:db8::1]:80".parse().unwrap();
        assert_eq!(
            addr.host,
            TargetHost::Ip("2001:db8::1".parse::<IpAddr>().unwrap())
        );
        assert_eq!(addr.port, 80);
    }

    #[test]
    fn test_target_addr_from_str_rejects_unbracketed_ipv6() {
        let err = "::1:443".parse::<TargetAddr>().unwrap_err();
        assert!(err.contains("unbracketed IPv6"));
    }

    #[test]
    fn test_target_addr_from_str_rejects_unclosed_bracket() {
        let err = "[::1:443".parse::<TargetAddr>().unwrap_err();
        assert!(err.contains("closing ']'"));
    }

    #[test]
    fn test_target_addr_display_brackets_ipv6() {
        let addr = TargetAddr {
            host: TargetHost::Ip("::1".parse().unwrap()),
            port: 443,
        };
        assert_eq!(addr.to_string(), "[::1]:443");
    }

    #[test]
    fn test_target_addr_display_does_not_bracket_ipv4() {
        let addr = TargetAddr {
            host: TargetHost::Ip("127.0.0.1".parse().unwrap()),
            port: 80,
        };
        assert_eq!(addr.to_string(), "127.0.0.1:80");
    }

    #[test]
    fn test_protocol_spec_runtime_disposition_is_exhaustive() {
        use eggress_uri::ProtocolSpec as S;
        // Every current `ProtocolSpec` variant has an explicit disposition.
        assert_eq!(eggress_uri::ProtocolSpec::all_variants().len(), 14);
        let cases: &[(S, Option<ProtocolId>)] = &[
            (S::Http, Some(ProtocolId::Http)),
            // Upstream adapter collapses to Http for listener dispatch.
            (S::HttpOnly, Some(ProtocolId::Http)),
            (S::Socks4, Some(ProtocolId::Socks4)),
            (S::Socks5, Some(ProtocolId::Socks5)),
            (S::Shadowsocks, Some(ProtocolId::Shadowsocks)),
            (S::ShadowsocksR, Some(ProtocolId::ShadowsocksR)),
            (S::Trojan, Some(ProtocolId::Trojan)),
            (S::Http2, Some(ProtocolId::Http2)),
            (S::Http3, Some(ProtocolId::Http3)),
            (S::Quic, Some(ProtocolId::Quic)),
            (S::WebSocket, Some(ProtocolId::WebSocket)),
            (S::Raw, Some(ProtocolId::Raw)),
            // Transport concept: Unix listeners serve Raw semantics.
            (S::Unix, Some(ProtocolId::Raw)),
            // Upstream-only transport fails explicitly.
            (S::Ssh, None),
        ];
        for (spec, expected) in cases {
            assert_eq!(
                ProtocolId::from_protocol_spec(*spec).ok(),
                *expected,
                "disposition for {spec:?}"
            );
        }
        assert_eq!(
            ProtocolId::from_protocol_spec(S::Ssh),
            Err(ProtocolConversionError::UpstreamOnlyTransport)
        );
    }
}