Skip to main content

pingora_core/protocols/tls/
mod.rs

1// Copyright 2026 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The TLS layer implementations
16
17pub mod digest;
18pub use digest::*;
19
20#[cfg(feature = "openssl_derived")]
21mod boringssl_openssl;
22
23#[cfg(feature = "openssl_derived")]
24pub use boringssl_openssl::*;
25
26#[cfg(feature = "rustls")]
27mod rustls;
28
29#[cfg(feature = "rustls")]
30pub use rustls::*;
31
32#[cfg(feature = "s2n")]
33mod s2n;
34
35#[cfg(feature = "s2n")]
36pub use s2n::*;
37
38#[cfg(not(feature = "any_tls"))]
39pub mod noop_tls;
40
41#[cfg(not(feature = "any_tls"))]
42pub use noop_tls::*;
43
44/// Containing type for a user callback to generate extensions for the `SslDigest` upon handshake
45/// completion.
46pub type HandshakeCompleteHook = std::sync::Arc<
47    dyn Fn(&TlsRef) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> + Send + Sync,
48>;
49
50/// The protocol for Application-Layer Protocol Negotiation
51#[derive(Hash, Clone, Debug, PartialEq, PartialOrd)]
52pub enum ALPN {
53    /// Prefer HTTP/1.1 only
54    H1,
55    /// Prefer HTTP/2 only
56    H2,
57    /// Prefer HTTP/2 over HTTP/1.1
58    H2H1,
59    /// Custom Protocol is stored in wire format (length-prefixed)
60    /// Wire format is precomputed at creation to avoid dangling references
61    Custom(CustomALPN),
62}
63
64/// Represents a Custom ALPN Protocol with a precomputed wire format and header offset.
65#[derive(Hash, Clone, Debug, PartialEq, PartialOrd)]
66pub struct CustomALPN {
67    wire: Vec<u8>,
68    header: usize,
69}
70
71impl CustomALPN {
72    /// Create a new CustomALPN from a protocol byte vector
73    pub fn new(proto: Vec<u8>) -> Self {
74        // Validate before setting
75        assert!(!proto.is_empty(), "Custom ALPN protocol must not be empty");
76        // RFC-7301
77        assert!(
78            proto.len() <= 255,
79            "ALPN protocol name must be 255 bytes or fewer"
80        );
81
82        match proto.as_slice() {
83            b"http/1.1" | b"h2" => {
84                panic!("Custom ALPN cannot be a reserved protocol (http/1.1 or h2)")
85            }
86            _ => {}
87        }
88        let mut wire = Vec::with_capacity(1 + proto.len());
89        wire.push(proto.len() as u8);
90        wire.extend_from_slice(&proto);
91
92        Self {
93            wire,
94            header: 1, // Header is always at index 1 since we prefix one length byte
95        }
96    }
97
98    /// Get the custom protocol name as a slice
99    pub fn protocol(&self) -> &[u8] {
100        &self.wire[self.header..]
101    }
102
103    /// Get the wire format used for ALPN negotiation
104    pub fn as_wire(&self) -> &[u8] {
105        &self.wire
106    }
107}
108
109impl std::fmt::Display for ALPN {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        match self {
112            ALPN::H1 => write!(f, "H1"),
113            ALPN::H2 => write!(f, "H2"),
114            ALPN::H2H1 => write!(f, "H2H1"),
115            ALPN::Custom(custom) => {
116                // extract protocol name, print as UTF-8 if possible, else judt itd raw bytes
117                match std::str::from_utf8(custom.protocol()) {
118                    Ok(s) => write!(f, "Custom({})", s),
119                    Err(_) => write!(f, "Custom({:?})", custom.protocol()),
120                }
121            }
122        }
123    }
124}
125
126impl ALPN {
127    /// Create a new ALPN according to the `max` and `min` version constraints
128    pub fn new(max: u8, min: u8) -> Self {
129        if max == 1 {
130            ALPN::H1
131        } else if min == 2 {
132            ALPN::H2
133        } else {
134            ALPN::H2H1
135        }
136    }
137
138    /// Return the max http version this [`ALPN`] allows
139    pub fn get_max_http_version(&self) -> u8 {
140        match self {
141            ALPN::H1 => 1,
142            ALPN::H2 | ALPN::H2H1 => 2,
143            ALPN::Custom(_) => 0,
144        }
145    }
146
147    /// Return the min http version this [`ALPN`] allows
148    pub fn get_min_http_version(&self) -> u8 {
149        match self {
150            ALPN::H1 | ALPN::H2H1 => 1,
151            ALPN::H2 => 2,
152            ALPN::Custom(_) => 0,
153        }
154    }
155
156    #[cfg(feature = "openssl_derived")]
157    pub(crate) fn to_wire_preference(&self) -> &[u8] {
158        // https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_alpn_select_cb.html
159        // "vector of nonempty, 8-bit length-prefixed, byte strings"
160        match self {
161            Self::H1 => b"\x08http/1.1",
162            Self::H2 => b"\x02h2",
163            Self::H2H1 => b"\x02h2\x08http/1.1",
164            Self::Custom(custom) => custom.as_wire(),
165        }
166    }
167
168    #[cfg(feature = "any_tls")]
169    pub(crate) fn from_wire_selected(raw: &[u8]) -> Option<Self> {
170        match raw {
171            b"http/1.1" => Some(Self::H1),
172            b"h2" => Some(Self::H2),
173            _ => Some(Self::Custom(CustomALPN::new(raw.to_vec()))),
174        }
175    }
176
177    #[cfg(feature = "rustls")]
178    pub(crate) fn to_wire_protocols(&self) -> Vec<Vec<u8>> {
179        match self {
180            ALPN::H1 => vec![b"http/1.1".to_vec()],
181            ALPN::H2 => vec![b"h2".to_vec()],
182            ALPN::H2H1 => vec![b"h2".to_vec(), b"http/1.1".to_vec()],
183            ALPN::Custom(custom) => vec![custom.protocol().to_vec()],
184        }
185    }
186
187    #[cfg(feature = "s2n")]
188    pub(crate) fn to_wire_protocols(&self) -> Vec<Vec<u8>> {
189        match self {
190            ALPN::H1 => vec![b"http/1.1".to_vec()],
191            ALPN::H2 => vec![b"h2".to_vec()],
192            ALPN::H2H1 => vec![b"h2".to_vec(), b"http/1.1".to_vec()],
193        }
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn test_valid_alpn_construction_and_versions() {
203        // Standard Protocols
204        assert_eq!(ALPN::H1.get_min_http_version(), 1);
205        assert_eq!(ALPN::H1.get_max_http_version(), 1);
206
207        assert_eq!(ALPN::H2.get_min_http_version(), 2);
208        assert_eq!(ALPN::H2.get_max_http_version(), 2);
209
210        assert_eq!(ALPN::H2H1.get_min_http_version(), 1);
211        assert_eq!(ALPN::H2H1.get_max_http_version(), 2);
212
213        // Custom Protocol
214        let custom_protocol = ALPN::Custom(CustomALPN::new("custom/1.0".into()));
215        assert_eq!(custom_protocol.get_min_http_version(), 0);
216        assert_eq!(custom_protocol.get_max_http_version(), 0);
217    }
218    #[test]
219    #[should_panic(expected = "Custom ALPN protocol must not be empty")]
220    fn test_empty_custom_alpn() {
221        let _ = ALPN::Custom(CustomALPN::new("".into()));
222    }
223    #[test]
224    #[should_panic(expected = "ALPN protocol name must be 255 bytes or fewer")]
225    fn test_large_custom_alpn() {
226        let large_alpn = vec![b'a'; 256];
227        let _ = ALPN::Custom(CustomALPN::new(large_alpn));
228    }
229    #[test]
230    #[should_panic(expected = "Custom ALPN cannot be a reserved protocol (http/1.1 or h2)")]
231    fn test_custom_h1_alpn() {
232        let _ = ALPN::Custom(CustomALPN::new("http/1.1".into()));
233    }
234    #[test]
235    #[should_panic(expected = "Custom ALPN cannot be a reserved protocol (http/1.1 or h2)")]
236    fn test_custom_h2_alpn() {
237        let _ = ALPN::Custom(CustomALPN::new("h2".into()));
238    }
239}