1use std::fmt;
11use std::io::{self, Read};
12use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
13use std::str::FromStr;
14
15pub const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
17
18const V1_PREFIX: &[u8] = b"PROXY ";
20
21const V1_MAX_LENGTH: usize = 107;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Header {
27 Local,
29 Proxy {
32 source: Option<SocketAddr>,
33 destination: Option<SocketAddr>,
34 },
35}
36
37impl Header {
38 pub fn source_or(self, connected: SocketAddr) -> SocketAddr {
40 match self {
41 Self::Proxy {
42 source: Some(source),
43 ..
44 } => source,
45 _ => connected,
46 }
47 }
48}
49
50#[derive(Debug)]
52pub enum HeaderError {
53 Io(io::Error),
54 Signature,
56 Line(&'static str),
58 Version(u8),
60 Command(u8),
62 Transport(u8),
64 Length {
66 family: u8,
67 length: u16,
68 },
69}
70
71impl fmt::Display for HeaderError {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 Self::Io(error) => write!(f, "PROXY protocol のヘッダーを読めません: {error}"),
75 Self::Signature => f.write_str("PROXY protocol のヘッダーで始まっていません"),
76 Self::Line(reason) => write!(f, "PROXY protocol v1 の行を読めません: {reason}"),
77 Self::Version(version) => write!(
78 f,
79 "PROXY protocol の版 {version} は読めません(バイナリの形は 2 だけ)"
80 ),
81 Self::Command(command) => {
82 write!(f, "PROXY protocol のコマンド {command:#x} は読めません")
83 }
84 Self::Transport(protocol) => write!(
85 f,
86 "PROXY protocol で TCP 以外({protocol:#x})を中継してきました"
87 ),
88 Self::Length { family, length } => write!(
89 f,
90 "PROXY protocol のアドレスの族 {family:#x} に、長さ {length} は足りません"
91 ),
92 }
93 }
94}
95
96impl std::error::Error for HeaderError {}
97
98impl From<io::Error> for HeaderError {
99 fn from(error: io::Error) -> Self {
100 Self::Io(error)
101 }
102}
103
104pub fn read_header(reader: &mut impl Read) -> Result<Header, HeaderError> {
107 let mut start = [0; 12];
109 reader.read_exact(&mut start)?;
110 if start == SIGNATURE {
111 read_v2(reader)
112 } else if start.starts_with(V1_PREFIX) {
113 read_v1(reader, &start)
114 } else {
115 Err(HeaderError::Signature)
116 }
117}
118
119fn read_v1(reader: &mut impl Read, start: &[u8]) -> Result<Header, HeaderError> {
121 let mut line = start.to_vec();
122 while !line.ends_with(b"\r\n") {
123 if line.len() >= V1_MAX_LENGTH {
124 return Err(HeaderError::Line("107 バイトのうちに行が終わりません"));
125 }
126 let mut byte = [0];
127 reader.read_exact(&mut byte)?;
128 line.push(byte[0]);
129 }
130 let text = std::str::from_utf8(&line[..line.len() - 2])
131 .ok()
132 .filter(|text| !text.contains(['\r', '\n']))
133 .ok_or(HeaderError::Line("ASCII の 1 行でない"))?;
134 let mut fields = text.split(' ').skip(1);
135 let ipv4 = match fields.next() {
136 Some("UNKNOWN") => {
138 return Ok(Header::Proxy {
139 source: None,
140 destination: None,
141 });
142 }
143 Some("TCP4") => true,
144 Some("TCP6") => false,
145 _ => return Err(HeaderError::Line("TCP4、TCP6、UNKNOWN のどれでもない")),
146 };
147 let fields: Vec<&str> = fields.collect();
148 let [source, destination, source_port, destination_port] = fields[..] else {
149 return Err(HeaderError::Line("アドレスとポートが 2 つずつでない"));
150 };
151 let ip = |text: &str| {
152 text.parse::<IpAddr>()
153 .ok()
154 .filter(|ip| ip.is_ipv4() == ipv4)
155 .ok_or(HeaderError::Line("アドレスが読めないか、族が合わない"))
156 };
157 let port = |text: &str| {
158 text.parse::<u16>()
159 .ok()
160 .filter(|_| text.bytes().all(|byte| byte.is_ascii_digit()))
161 .ok_or(HeaderError::Line("ポートが読めない"))
162 };
163 Ok(Header::Proxy {
164 source: Some(SocketAddr::new(ip(source)?, port(source_port)?)),
165 destination: Some(SocketAddr::new(ip(destination)?, port(destination_port)?)),
166 })
167}
168
169fn read_v2(reader: &mut impl Read) -> Result<Header, HeaderError> {
171 let mut fixed = [0; 4];
172 reader.read_exact(&mut fixed)?;
173 let (version, command) = (fixed[0] >> 4, fixed[0] & 0x0f);
174 if version != 2 {
175 return Err(HeaderError::Version(version));
176 }
177 let (family, protocol) = (fixed[1] >> 4, fixed[1] & 0x0f);
178 let length = u16::from_be_bytes([fixed[2], fixed[3]]);
179 let mut rest = vec![0; usize::from(length)];
180 reader.read_exact(&mut rest)?;
181 match command {
182 0 => return Ok(Header::Local),
184 1 => {}
185 _ => return Err(HeaderError::Command(command)),
186 }
187 if family != 0 && protocol != 1 {
189 return Err(HeaderError::Transport(protocol));
190 }
191 let short = || HeaderError::Length {
192 family: fixed[1],
193 length,
194 };
195 let (source, destination) = match family {
196 1 => {
197 let address: &[u8; 12] = rest
198 .get(..12)
199 .and_then(|a| a.try_into().ok())
200 .ok_or_else(short)?;
201 let ip = |at: usize| {
202 IpAddr::V4(Ipv4Addr::from(
203 <[u8; 4]>::try_from(&address[at..at + 4]).expect("4 bytes"),
204 ))
205 };
206 let port = |at: usize| u16::from_be_bytes([address[at], address[at + 1]]);
207 (
208 SocketAddr::new(ip(0), port(8)),
209 SocketAddr::new(ip(4), port(10)),
210 )
211 }
212 2 => {
213 let address: &[u8; 36] = rest
214 .get(..36)
215 .and_then(|a| a.try_into().ok())
216 .ok_or_else(short)?;
217 let ip = |at: usize| {
218 IpAddr::V6(Ipv6Addr::from(
219 <[u8; 16]>::try_from(&address[at..at + 16]).expect("16 bytes"),
220 ))
221 };
222 let port = |at: usize| u16::from_be_bytes([address[at], address[at + 1]]);
223 (
224 SocketAddr::new(ip(0), port(32)),
225 SocketAddr::new(ip(16), port(34)),
226 )
227 }
228 _ => {
230 return Ok(Header::Proxy {
231 source: None,
232 destination: None,
233 });
234 }
235 };
236 Ok(Header::Proxy {
237 source: Some(source),
238 destination: Some(destination),
239 })
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub struct IpRange {
245 address: IpAddr,
246 prefix: u8,
247}
248
249impl IpRange {
250 pub fn contains(&self, ip: IpAddr) -> bool {
252 let ip = match ip {
253 IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
254 IpAddr::V4(_) => ip,
255 };
256 match (self.address, ip) {
257 (IpAddr::V4(range), IpAddr::V4(ip)) => {
258 let mask = u32::MAX
259 .checked_shl(32 - u32::from(self.prefix))
260 .unwrap_or(0);
261 u32::from(range) & mask == u32::from(ip) & mask
262 }
263 (IpAddr::V6(range), IpAddr::V6(ip)) => {
264 let mask = u128::MAX
265 .checked_shl(128 - u32::from(self.prefix))
266 .unwrap_or(0);
267 u128::from(range) & mask == u128::from(ip) & mask
268 }
269 _ => false,
270 }
271 }
272}
273
274impl FromStr for IpRange {
275 type Err = String;
276
277 fn from_str(text: &str) -> Result<Self, Self::Err> {
278 let invalid =
279 || format!("アドレスの範囲 {text:?} を読めません(たとえば 10.0.0.0/8、::1)");
280 let (address, prefix) = text
281 .split_once('/')
282 .map_or((text, None), |(a, p)| (a, Some(p)));
283 let address: IpAddr = address.parse().map_err(|_| invalid())?;
284 let bits = if address.is_ipv4() { 32 } else { 128 };
285 let prefix = match prefix {
286 None => bits,
287 Some(prefix) => prefix
288 .parse()
289 .ok()
290 .filter(|&p| p <= bits)
291 .ok_or_else(invalid)?,
292 };
293 Ok(Self { address, prefix })
294 }
295}
296
297impl fmt::Display for IpRange {
298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299 write!(f, "{}/{}", self.address, self.prefix)
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use super::*;
306
307 fn header(command: u8, family: u8, body: &[u8]) -> Vec<u8> {
308 let length = u16::try_from(body.len()).unwrap().to_be_bytes();
309 [&SIGNATURE[..], &[0x20 | command, family], &length, body].concat()
310 }
311
312 #[test]
313 fn reads_ipv4_and_leaves_the_rest() {
314 let body = [
315 192, 0, 2, 1, 198, 51, 100, 7, 0x1e, 0xdc, 0x1e, 0xdc, 0x04, 0x00, 0x01, 0x00,
320 ];
321 let mut bytes = header(1, 0x11, &body);
322 bytes.extend_from_slice(b"\x16tls");
323 let mut reader = &bytes[..];
324 let read = read_header(&mut reader).unwrap();
325 assert_eq!(
326 read,
327 Header::Proxy {
328 source: Some("192.0.2.1:7900".parse().unwrap()),
329 destination: Some("198.51.100.7:7900".parse().unwrap()),
330 }
331 );
332 assert_eq!(reader, b"\x16tls");
333 }
334
335 #[test]
336 fn reads_ipv6() {
337 let source: Ipv6Addr = "2001:db8::1".parse().unwrap();
338 let destination: Ipv6Addr = "2001:db8::2".parse().unwrap();
339 let body = [
340 &source.octets()[..],
341 &destination.octets(),
342 &[0x30, 0x39, 0x1e, 0xdc],
343 ]
344 .concat();
345 let read = read_header(&mut &header(1, 0x21, &body)[..]).unwrap();
346 assert_eq!(
347 read.source_or("127.0.0.1:1".parse().unwrap()),
348 "[2001:db8::1]:12345".parse().unwrap()
349 );
350 }
351
352 #[test]
353 fn local_and_unspecified_keep_the_connection_address() {
354 let connected: SocketAddr = "127.0.0.1:5555".parse().unwrap();
355 let local = read_header(&mut &header(0, 0x00, &[])[..]).unwrap();
356 assert_eq!(local, Header::Local);
357 assert_eq!(local.source_or(connected), connected);
358 let unspecified = read_header(&mut &header(1, 0x00, &[])[..]).unwrap();
359 assert_eq!(unspecified.source_or(connected), connected);
360 }
361
362 #[test]
363 fn rejects_what_it_cannot_read() {
364 let tls = [
365 0x16, 0x03, 0x01, 0x02, 0x00, 0x01, 0x00, 0x01, 0xfc, 3, 3, 0, 0, 0, 0, 0,
366 ];
367 assert!(matches!(
368 read_header(&mut &tls[..]),
369 Err(HeaderError::Signature)
370 ));
371 let mut v1 = header(1, 0x11, &[0; 12]);
372 v1[12] = 0x11;
373 assert!(matches!(
374 read_header(&mut &v1[..]),
375 Err(HeaderError::Version(1))
376 ));
377 assert!(matches!(
378 read_header(&mut &header(2, 0x11, &[0; 12])[..]),
379 Err(HeaderError::Command(2))
380 ));
381 assert!(matches!(
382 read_header(&mut &header(1, 0x12, &[0; 12])[..]),
383 Err(HeaderError::Transport(2))
384 ));
385 assert!(matches!(
386 read_header(&mut &header(1, 0x11, &[0; 8])[..]),
387 Err(HeaderError::Length { .. })
388 ));
389 let mut cut = header(1, 0x11, &[0; 12]);
391 cut.truncate(20);
392 assert!(matches!(
393 read_header(&mut &cut[..]),
394 Err(HeaderError::Io(_))
395 ));
396 }
397
398 #[test]
399 fn reads_v1_and_leaves_the_rest() {
400 let mut reader = &b"PROXY TCP4 192.0.2.1 198.51.100.7 40000 7900\r\n\x16tls"[..];
401 assert_eq!(
402 read_header(&mut reader).unwrap(),
403 Header::Proxy {
404 source: Some("192.0.2.1:40000".parse().unwrap()),
405 destination: Some("198.51.100.7:7900".parse().unwrap()),
406 }
407 );
408 assert_eq!(reader, b"\x16tls");
409 let six = read_header(&mut &b"PROXY TCP6 2001:db8::1 2001:db8::2 12345 7900\r\n"[..]);
410 assert_eq!(
411 six.unwrap().source_or("127.0.0.1:1".parse().unwrap()),
412 "[2001:db8::1]:12345".parse().unwrap()
413 );
414 let connected: SocketAddr = "127.0.0.1:5555".parse().unwrap();
415 let unknown = read_header(&mut &b"PROXY UNKNOWN ffff::1 whatever\r\n"[..]).unwrap();
416 assert_eq!(unknown.source_or(connected), connected);
417 }
418
419 #[test]
420 fn rejects_malformed_v1_lines() {
421 for line in [
422 &b"PROXY TCP4 192.0.2.1 198.51.100.7 40000\r\n"[..],
423 b"PROXY TCP4 2001:db8::1 198.51.100.7 40000 7900\r\n",
424 b"PROXY TCP6 192.0.2.1 198.51.100.7 40000 7900\r\n",
425 b"PROXY TCP4 192.0.2.1 198.51.100.7 +4000 7900\r\n",
426 b"PROXY TCP4 192.0.2.1 198.51.100.7 70000 7900\r\n",
427 b"PROXY UDP4 192.0.2.1 198.51.100.7 40000 7900\r\n",
428 b"PROXY TCP4 192.0.2.1\r\n198.51.100.7 40000 7900\r\n",
429 ] {
430 assert!(
431 matches!(read_header(&mut &line[..]), Err(HeaderError::Line(_))),
432 "{}",
433 String::from_utf8_lossy(line)
434 );
435 }
436 let long = [&b"PROXY "[..], &[b'x'; 200]].concat();
438 assert!(matches!(
439 read_header(&mut &long[..]),
440 Err(HeaderError::Line(_))
441 ));
442 }
443
444 #[test]
445 fn ranges() {
446 let range: IpRange = "10.0.0.0/8".parse().unwrap();
447 assert!(range.contains("10.1.2.3".parse().unwrap()));
448 assert!(range.contains("::ffff:10.1.2.3".parse().unwrap()));
449 assert!(!range.contains("11.0.0.1".parse().unwrap()));
450 let one: IpRange = "127.0.0.1".parse().unwrap();
451 assert!(one.contains("127.0.0.1".parse().unwrap()));
452 assert!(!one.contains("127.0.0.2".parse().unwrap()));
453 let v6: IpRange = "fd00::/8".parse().unwrap();
454 assert!(v6.contains("fd12::1".parse().unwrap()));
455 assert!(!v6.contains("10.0.0.1".parse().unwrap()));
456 let all: IpRange = "0.0.0.0/0".parse().unwrap();
457 assert!(all.contains("203.0.113.9".parse().unwrap()));
458 assert_eq!(one.to_string(), "127.0.0.1/32");
459 assert!("10.0.0.0/33".parse::<IpRange>().is_err());
460 assert!("example".parse::<IpRange>().is_err());
461 }
462}