eggfetch_http_connect/
request.rs1use std::fmt;
8
9use crate::error::ConnectError;
10use crate::target::ConnectTarget;
11
12pub struct ConnectRequest<'a> {
20 pub target: &'a ConnectTarget,
22 pub proxy_authorization: Option<&'a str>,
24 pub extra_headers: &'a [(String, Vec<u8>)],
26 pub max_head_bytes: usize,
28}
29
30impl fmt::Debug for ConnectRequest<'_> {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 let redacted_extra: Vec<(&str, String)> = self
36 .extra_headers
37 .iter()
38 .map(|(name, value)| {
39 if name.eq_ignore_ascii_case("proxy-authorization") {
40 (name.as_str(), String::from("<redacted>"))
41 } else {
42 (name.as_str(), String::from_utf8_lossy(value).into_owned())
43 }
44 })
45 .collect();
46 f.debug_struct("ConnectRequest")
47 .field("target", &self.target)
48 .field(
49 "proxy_authorization",
50 &self.proxy_authorization.map(|_| "<redacted>"),
51 )
52 .field("extra_headers", &redacted_extra)
53 .field("max_head_bytes", &self.max_head_bytes)
54 .finish()
55 }
56}
57
58pub fn basic_auth_value(username: &str, password: &str) -> Result<String, ConnectError> {
66 if username.contains(':') {
67 return Err(ConnectError::InvalidCredentials);
68 }
69 for value in [username, password] {
70 for c in value.chars() {
71 if c == '\r' || c == '\n' || c == '\0' || c.is_control() || c == '\u{7f}' {
72 return Err(ConnectError::InvalidCredentials);
73 }
74 }
75 }
76 {
77 use base64::Engine as _;
78 let credential = format!("{username}:{password}");
79 let encoded = base64::engine::general_purpose::STANDARD.encode(credential.as_bytes());
80 Ok(format!("Basic {encoded}"))
81 }
82}
83
84pub fn encode_connect_request(request: &ConnectRequest<'_>) -> Result<Vec<u8>, ConnectError> {
104 let authority = request.target.authority();
105
106 if let Some(auth) = request.proxy_authorization {
107 validate_header_value_bytes(auth.as_bytes())?;
108 }
109
110 let mut extra_auth_count = 0_usize;
114 for (name, value) in request.extra_headers {
115 validate_header_name(name)?;
116 validate_header_value_bytes(value)?;
117 if name.eq_ignore_ascii_case("proxy-authorization") {
118 extra_auth_count += 1;
119 }
120 if name.eq_ignore_ascii_case("host") {
121 return Err(ConnectError::ReservedHeader);
122 }
123 }
124 if request.proxy_authorization.is_some() && extra_auth_count > 0 {
125 return Err(ConnectError::DuplicateAuthorization);
126 }
127 if extra_auth_count > 1 {
128 return Err(ConnectError::DuplicateAuthorization);
129 }
130
131 let max = request.max_head_bytes;
132 let mut out = Vec::new();
133
134 let request_line = format!("CONNECT {authority} HTTP/1.1\r\n");
135 let host_line = format!("Host: {authority}\r\n");
136 let mut len = 0_usize;
139 for chunk_len in [
140 request_line.len(),
141 host_line.len(),
142 request
143 .proxy_authorization
144 .map_or(0, |v| "Proxy-Authorization: ".len() + v.len() + 2),
145 ] {
146 len = len
147 .checked_add(chunk_len)
148 .ok_or(ConnectError::RequestHeadTooLarge {
149 len: usize::MAX,
150 max,
151 })?;
152 if len > max {
153 return Err(ConnectError::RequestHeadTooLarge { len, max });
154 }
155 }
156 for (name, value) in request.extra_headers {
157 let header_len = name.len().checked_add(2 + value.len() + 2).ok_or(
158 ConnectError::RequestHeadTooLarge {
159 len: usize::MAX,
160 max,
161 },
162 )?;
163 len = len
164 .checked_add(header_len)
165 .ok_or(ConnectError::RequestHeadTooLarge {
166 len: usize::MAX,
167 max,
168 })?;
169 if len > max {
170 return Err(ConnectError::RequestHeadTooLarge { len, max });
171 }
172 }
173 len = len
174 .checked_add(2)
175 .ok_or(ConnectError::RequestHeadTooLarge {
176 len: usize::MAX,
177 max,
178 })?;
179 if len > max {
180 return Err(ConnectError::RequestHeadTooLarge { len, max });
181 }
182
183 out.extend_from_slice(request_line.as_bytes());
184 out.extend_from_slice(host_line.as_bytes());
185 if let Some(auth) = request.proxy_authorization {
186 out.extend_from_slice(b"Proxy-Authorization: ");
187 out.extend_from_slice(auth.as_bytes());
188 out.extend_from_slice(b"\r\n");
189 }
190 for (name, value) in request.extra_headers {
191 out.extend_from_slice(name.as_bytes());
192 out.extend_from_slice(b": ");
193 out.extend_from_slice(value);
194 out.extend_from_slice(b"\r\n");
195 }
196 out.extend_from_slice(b"\r\n");
197 debug_assert_eq!(out.len(), len);
198 Ok(out)
199}
200
201fn validate_header_name(name: &str) -> Result<(), ConnectError> {
203 if name.is_empty() || name.len() > 256 {
204 return Err(ConnectError::InvalidHeader);
205 }
206 for byte in name.bytes() {
207 if !is_token_byte(byte) {
208 return Err(ConnectError::InvalidHeader);
209 }
210 }
211 Ok(())
212}
213
214fn validate_header_value_bytes(value: &[u8]) -> Result<(), ConnectError> {
216 for byte in value {
217 if matches!(byte, 0x00..=0x08 | 0x0A..=0x1F | 0x7F) {
220 return Err(ConnectError::InvalidHeader);
221 }
222 }
223 Ok(())
224}
225
226fn is_token_byte(byte: u8) -> bool {
228 matches!(
229 byte,
230 b'!' | b'#'
231 | b'$'
232 | b'%'
233 | b'&'
234 | b'\''
235 | b'*'
236 | b'+'
237 | b'-'
238 | b'.'
239 | b'^'
240 | b'_'
241 | b'`'
242 | b'|'
243 | b'~'
244 | b'0'..=b'9'
245 | b'A'..=b'Z'
246 | b'a'..=b'z'
247 )
248}