1use crate::http::encoding::Encoder;
3use crate::http::header::{
4 ACCEPT_ENCODING, CONTENT_ENCODING, ContentEncoding, HeaderMap, HeaderValue, VARY,
5};
6use crate::service::{Ctx, Middleware, Service};
7use crate::web::{BodyEncoding, State, WebRequest, WebResponse};
8
9#[derive(Debug, Clone)]
10pub struct Compress {
41 enc: ContentEncoding,
42}
43
44impl Compress {
45 pub fn new(encoding: ContentEncoding) -> Self {
50 Compress { enc: encoding }
51 }
52}
53
54impl Default for Compress {
55 fn default() -> Self {
56 Compress::new(ContentEncoding::Auto)
57 }
58}
59
60impl<S, St> Middleware<S, St> for Compress {
61 type Service = CompressMiddleware<S>;
62
63 fn create(&self, _: &St, service: S) -> Self::Service {
64 CompressMiddleware {
65 service,
66 encoding: self.enc,
67 }
68 }
69}
70
71#[derive(Debug)]
72pub struct CompressMiddleware<S> {
73 service: S,
74 encoding: ContentEncoding,
75}
76
77impl<S, St, In> Service<St, WebRequest<In>> for CompressMiddleware<S>
78where
79 S: Service<St, WebRequest<In>, Res = WebResponse>,
80 St: State,
81{
82 type Res = WebResponse;
83 type Error = S::Error;
84
85 crate::forward!(St, service);
86
87 async fn call(
88 &self,
89 req: WebRequest<In>,
90 ctx: Ctx<'_, Self, St>,
91 ) -> Result<WebResponse, S::Error> {
92 let values = req
94 .headers()
95 .get_all(&ACCEPT_ENCODING)
96 .filter_map(|val| val.to_str().ok());
97 let encoding = AcceptEncoding::parse(values, self.encoding);
98
99 let mut resp = ctx.call(&self.service, req).await?;
100
101 let enc = if let Some(enc) = resp.response().get_encoding() {
102 enc
103 } else {
104 if self.encoding != ContentEncoding::Identity
105 && !resp.headers().contains_key(CONTENT_ENCODING)
106 {
107 add_vary(resp.headers_mut());
108 }
109 encoding
110 };
111
112 Ok(resp.map_body(move |head, body| Encoder::response(enc, head, body)))
113 }
114}
115
116fn add_vary(headers: &mut HeaderMap) {
118 let covered = headers
119 .get_all(VARY)
120 .filter_map(|val| val.to_str().ok())
121 .flat_map(|val| val.split(','))
122 .map(str::trim)
123 .any(|name| name == "*" || name.eq_ignore_ascii_case("accept-encoding"));
124 if !covered {
125 headers.append(VARY, HeaderValue::from_static("accept-encoding"));
126 }
127}
128
129const WILDCARD: [ContentEncoding; 3] = [
131 ContentEncoding::Zstd,
132 ContentEncoding::Gzip,
133 ContentEncoding::Deflate,
134];
135
136#[derive(Debug, PartialEq)]
137struct AcceptEncoding {
138 encoding: Option<ContentEncoding>,
140 q: u16,
142}
143
144impl AcceptEncoding {
145 fn new(tag: &str) -> Option<AcceptEncoding> {
146 let mut parts = tag.split(';');
147 let name = parts.next()?.trim();
148 if name.is_empty() {
149 return None;
150 }
151 let encoding = if name == "*" {
153 None
154 } else {
155 Some(name.parse().ok()?)
156 };
157
158 let q = parts
160 .filter_map(|param| param.split_once('='))
161 .find(|(name, _)| name.trim().eq_ignore_ascii_case("q"))
162 .map_or(1000, |(_, val)| parse_q(val.trim()).unwrap_or(0));
163 Some(AcceptEncoding { encoding, q })
164 }
165
166 fn parse<'a, I>(values: I, encoding: ContentEncoding) -> ContentEncoding
173 where
174 I: Iterator<Item = &'a str>,
175 {
176 let mut listed: Vec<(ContentEncoding, u16)> = Vec::new();
177 let mut wildcard = None;
178 for item in values.flat_map(|val| val.split(',')) {
179 match AcceptEncoding::new(item) {
180 Some(AcceptEncoding {
181 encoding: Some(enc),
182 q,
183 }) => listed.push((enc, q)),
184 Some(AcceptEncoding { encoding: None, q }) => {
185 wildcard.get_or_insert(q);
186 }
187 None => {}
188 }
189 }
190 let weight = |enc: ContentEncoding| {
191 listed
192 .iter()
193 .find(|(e, _)| *e == enc)
194 .map(|(_, q)| *q)
195 .or(wildcard)
196 .unwrap_or(0)
197 };
198 let identity = weight(ContentEncoding::Identity);
199
200 if encoding != ContentEncoding::Auto {
201 let q = weight(encoding);
202 return if q > 0 && q >= identity {
203 encoding
204 } else {
205 ContentEncoding::Identity
206 };
207 }
208
209 let mut best: Option<(ContentEncoding, u16)> = None;
210 let candidates = listed.iter().map(|(enc, _)| *enc).chain(WILDCARD);
211 for enc in candidates.filter(|enc| Encoder::can_encode(*enc)) {
212 let q = weight(enc);
213 let better = match best {
214 None => q > 0,
215 Some((b, bq)) => q > bq || (q == bq && enc.quality() > b.quality()),
216 };
217 if better {
218 best = Some((enc, q));
219 }
220 }
221 match best {
222 Some((enc, q)) if q >= identity => enc,
223 _ => ContentEncoding::Identity,
224 }
225 }
226}
227
228fn parse_q(val: &str) -> Option<u16> {
230 let (int, frac) = match val.split_once('.') {
231 Some((int, frac)) => (int, frac),
232 None => (val, ""),
233 };
234 if frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
235 return None;
236 }
237 let int = match int {
238 "0" => 0,
239 "1" => 1000,
240 _ => return None,
241 };
242 let frac = frac
243 .bytes()
244 .zip([100, 10, 1])
245 .map(|(b, scale)| u16::from(b - b'0') * scale)
246 .sum::<u16>();
247 if int + frac > 1000 { None } else { Some(int + frac) }
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 fn parse(raw: &str, encoding: ContentEncoding) -> ContentEncoding {
255 AcceptEncoding::parse([raw].into_iter(), encoding)
256 }
257
258 #[test]
264 fn test_parse_q() {
265 for (val, q) in [
266 ("0", 0),
267 ("0.", 0),
268 ("0.5", 500),
269 ("0.05", 50),
270 ("0.125", 125),
271 ("0.999", 999),
272 ("1", 1000),
273 ("1.", 1000),
274 ("1.000", 1000),
275 ] {
276 assert_eq!(parse_q(val), Some(q), "{val}");
277 }
278 for val in [
279 "", ".5", "0.1234", "1.001", "1.5", "2", "-0", "0.a", "0.00a", "01", "abc",
280 ] {
281 assert_eq!(parse_q(val), None, "{val}");
282 }
283 }
284
285 #[test]
292 fn test_accept_encoding_entry() {
293 let entry = |tag| AcceptEncoding::new(tag).unwrap();
294 assert_eq!(
295 entry("gzip"),
296 AcceptEncoding {
297 encoding: Some(ContentEncoding::Gzip),
298 q: 1000
299 }
300 );
301 assert_eq!(entry(" gzip ; q=0.5 ").q, 500);
302 assert_eq!(entry("gzip;Q=0.5").q, 500);
303 assert_eq!(entry("gzip;level=1;q=0.25").q, 250);
304 assert_eq!(entry("gzip;q=abc").q, 0);
305 assert_eq!(entry("gzip;0.8").q, 1000);
306 assert_eq!(entry("*;q=0.1").encoding, None);
307 assert_eq!(
308 entry("identity;q=0").encoding,
309 Some(ContentEncoding::Identity)
310 );
311 assert!(AcceptEncoding::new(" ").is_none());
312 assert!(AcceptEncoding::new("compress").is_none());
313 assert!(AcceptEncoding::new("gizp;q=1").is_none());
314 }
315
316 #[test]
322 fn test_auto_skips_unsupported_encodings() {
323 let auto = ContentEncoding::Auto;
324 assert_eq!(
325 parse("gzip, deflate, br, zstd", auto),
326 ContentEncoding::Zstd
327 );
328 assert_eq!(parse("gzip, deflate, br", auto), ContentEncoding::Gzip);
329 assert_eq!(parse("br, deflate", auto), ContentEncoding::Deflate);
330 assert_eq!(parse("br", auto), ContentEncoding::Identity);
331 assert_eq!(parse("gzip, br", ContentEncoding::Br), ContentEncoding::Br);
332 assert_eq!(parse(" br , gzip ; q=1.0 ", auto), ContentEncoding::Gzip);
333 assert_eq!(parse("", auto), ContentEncoding::Identity);
334 }
335
336 #[test]
342 fn test_auto_honours_q() {
343 let auto = ContentEncoding::Auto;
344 assert_eq!(parse("gzip;q=0.5, zstd;q=0.1", auto), ContentEncoding::Gzip);
345 assert_eq!(
346 parse("deflate;q=0.9, gzip;q=0.8", auto),
347 ContentEncoding::Deflate
348 );
349 assert_eq!(parse("zstd;q=0, gzip", auto), ContentEncoding::Gzip);
350 assert_eq!(parse("gzip;q=0", auto), ContentEncoding::Identity);
351 assert_eq!(parse("gzip;q=abc", auto), ContentEncoding::Identity);
352 assert_eq!(parse("gzip;q=2, deflate", auto), ContentEncoding::Deflate);
353 assert_eq!(parse("gzip, zstd;q=0", auto), ContentEncoding::Gzip);
354 assert_eq!(parse("gzip;q=0, gzip", auto), ContentEncoding::Identity);
356 assert_eq!(
358 parse("deflate;q=0.5, gzip;q=0.5, zstd;q=0.5", auto),
359 ContentEncoding::Zstd
360 );
361 assert_eq!(parse("deflate, gzip", auto), ContentEncoding::Gzip);
362 assert_eq!(parse("x-gzip", auto), ContentEncoding::Gzip);
363 }
364
365 #[test]
371 fn test_auto_wildcard() {
372 let auto = ContentEncoding::Auto;
373 assert_eq!(parse("*", auto), ContentEncoding::Zstd);
374 assert_eq!(parse("*;q=0", auto), ContentEncoding::Identity);
375 assert_eq!(parse("*;q=0.5, zstd;q=0", auto), ContentEncoding::Gzip);
376 assert_eq!(
377 parse("zstd;q=0, gzip;q=0, *", auto),
378 ContentEncoding::Deflate
379 );
380 assert_eq!(parse("*;q=0.5, deflate", auto), ContentEncoding::Deflate);
381 assert_eq!(parse("gzip;q=0.1, *;q=0.5", auto), ContentEncoding::Zstd);
382 assert_eq!(parse("*;q=0, gzip;q=0.1", auto), ContentEncoding::Gzip);
383 assert_eq!(parse("*;q=0.5, *", auto), ContentEncoding::Zstd);
384 assert_eq!(parse("*;q=0, *, zstd;q=0", auto), ContentEncoding::Identity);
385 }
386
387 #[test]
393 fn test_explicit_encoding() {
394 let gzip = ContentEncoding::Gzip;
395 assert_eq!(parse("gzip", gzip), gzip);
396 assert_eq!(parse("zstd", gzip), ContentEncoding::Identity);
397 assert_eq!(parse("gzip;q=0", gzip), ContentEncoding::Identity);
398 assert_eq!(parse("gzip;q=0.001", gzip), gzip);
399 assert_eq!(parse("*", gzip), gzip);
400 assert_eq!(parse("*;q=0", gzip), ContentEncoding::Identity);
401 assert_eq!(parse("*, gzip;q=0", gzip), ContentEncoding::Identity);
402 assert_eq!(parse("*;q=0, gzip", gzip), gzip);
403 }
404
405 #[test]
414 fn test_identity_preference() {
415 let auto = ContentEncoding::Auto;
416 let gzip = ContentEncoding::Gzip;
417 let id = ContentEncoding::Identity;
418 assert_eq!(parse("identity;q=1, gzip;q=0.1", auto), id);
419 assert_eq!(parse("identity;q=0.5, gzip;q=0.5", auto), gzip);
420 assert_eq!(parse("identity;q=0.4, gzip;q=0.5", auto), gzip);
421 assert_eq!(parse("*, gzip;q=0.1", auto), ContentEncoding::Zstd);
422 assert_eq!(parse("*, zstd;q=0.1, gzip;q=0.1, deflate;q=0.1", auto), id);
423 assert_eq!(parse("gzip;q=0.1", auto), gzip);
424 assert_eq!(parse("identity;q=1, gzip;q=0.1", gzip), id);
425 assert_eq!(parse("identity;q=0.1, gzip;q=0.1", gzip), gzip);
426 assert_eq!(parse("*, gzip;q=0.5", gzip), id);
427 assert_eq!(parse("identity;q=0, *;q=0.5, gzip;q=0.1", gzip), gzip);
428 }
429
430 #[test]
436 fn test_repeated_headers() {
437 let values = ["zstd;q=0", "gzip;q=0.5, deflate;q=0.1"];
438 assert_eq!(
439 AcceptEncoding::parse(values.into_iter(), ContentEncoding::Auto),
440 ContentEncoding::Gzip
441 );
442 }
443
444 #[crate::rt_test]
451 async fn test_compress_accept_encoding() {
452 use crate::http::header::{CONTENT_ENCODING, HeaderValue};
453 use crate::web::test::{TestRequest, call_service, init_service};
454 use crate::web::{self, App, HttpResponse};
455
456 let srv = init_service(App::new().middleware(Compress::default()).route(
457 "/",
458 web::get().to(async || HttpResponse::Ok().body("a".repeat(1024))),
459 ))
460 .await;
461
462 let req = TestRequest::default()
463 .header(ACCEPT_ENCODING, "gzip")
464 .to_request();
465 let resp = call_service(&srv, req).await;
466 assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");
467
468 let req = TestRequest::default()
469 .header(
470 ACCEPT_ENCODING,
471 HeaderValue::from_bytes(b"gzip\xff").unwrap(),
472 )
473 .to_request();
474 let resp = call_service(&srv, req).await;
475 assert!(resp.headers().get(CONTENT_ENCODING).is_none());
476
477 let req = TestRequest::default()
478 .header(ACCEPT_ENCODING, "zstd;q=0")
479 .header(ACCEPT_ENCODING, "gzip;q=0.5")
480 .to_request();
481 let resp = call_service(&srv, req).await;
482 assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "gzip");
483
484 let req = TestRequest::default()
485 .header(
486 ACCEPT_ENCODING,
487 HeaderValue::from_bytes(b"zstd\xff").unwrap(),
488 )
489 .header(ACCEPT_ENCODING, "deflate")
490 .to_request();
491 let resp = call_service(&srv, req).await;
492 assert_eq!(resp.headers().get(CONTENT_ENCODING).unwrap(), "deflate");
493
494 let req = TestRequest::default()
495 .header(ACCEPT_ENCODING, "gzip;q=0")
496 .to_request();
497 let resp = call_service(&srv, req).await;
498 assert!(resp.headers().get(CONTENT_ENCODING).is_none());
499 }
500
501 #[crate::rt_test]
511 async fn test_compress_vary() {
512 use crate::http::header::{CONTENT_ENCODING, VARY};
513 use crate::web::test::{TestRequest, call_service, init_service};
514 use crate::web::{self, App, HttpResponse};
515
516 fn body() -> String {
517 "a".repeat(1024)
518 }
519 let srv = init_service(
520 App::new()
521 .middleware(Compress::default())
522 .route("/", web::get().to(async || HttpResponse::Ok().body(body())))
523 .route(
524 "/vary",
525 web::get().to(async || HttpResponse::Ok().header(VARY, "origin").body(body())),
526 )
527 .route(
528 "/star",
529 web::get().to(async || HttpResponse::Ok().header(VARY, "*").body(body())),
530 )
531 .route(
532 "/has",
533 web::get().to(async || {
534 HttpResponse::Ok()
535 .header(VARY, "Origin, Accept-Encoding")
536 .body(body())
537 }),
538 )
539 .route(
540 "/override",
541 web::get().to(async || {
542 HttpResponse::Ok()
543 .encoding(ContentEncoding::Identity)
544 .body("a".repeat(1024))
545 }),
546 )
547 .route(
548 "/encoded",
549 web::get()
550 .to(async || HttpResponse::Ok().header(CONTENT_ENCODING, "br").body("a")),
551 ),
552 )
553 .await;
554 let vary = async |path: &str, accept: &str| {
555 let req = TestRequest::with_uri(path)
556 .header(ACCEPT_ENCODING, accept)
557 .to_request();
558 let resp = call_service(&srv, req).await;
559 resp.headers()
560 .get_all(VARY)
561 .map(|v| v.to_str().unwrap().to_string())
562 .collect::<Vec<_>>()
563 };
564
565 assert_eq!(vary("/", "gzip").await, ["accept-encoding"]);
566 assert_eq!(vary("/", "identity").await, ["accept-encoding"]);
567 assert_eq!(vary("/vary", "gzip").await, ["origin", "accept-encoding"]);
568 assert_eq!(vary("/star", "gzip").await, ["*"]);
569 assert_eq!(vary("/has", "gzip").await, ["Origin, Accept-Encoding"]);
570 assert_eq!(vary("/override", "gzip").await, Vec::<String>::new());
571 assert_eq!(vary("/encoded", "gzip").await, Vec::<String>::new());
572
573 let srv = init_service(
574 App::new()
575 .middleware(Compress::new(ContentEncoding::Identity))
576 .route("/", web::get().to(async || HttpResponse::Ok().body(body()))),
577 )
578 .await;
579 let req = TestRequest::default()
580 .header(ACCEPT_ENCODING, "gzip")
581 .to_request();
582 let resp = call_service(&srv, req).await;
583 assert!(resp.headers().get(VARY).is_none());
584 assert!(resp.headers().get(CONTENT_ENCODING).is_none());
585 }
586}