logo
  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
//! For middleware documentation, see [`Compress`].

use std::{
    cmp,
    convert::TryFrom as _,
    future::Future,
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use actix_http::{
    body::{EitherBody, MessageBody},
    encoding::Encoder,
    header::{ContentEncoding, ACCEPT_ENCODING},
    StatusCode,
};
use actix_service::{Service, Transform};
use actix_utils::future::{ok, Either, Ready};
use futures_core::ready;
use once_cell::sync::Lazy;
use pin_project_lite::pin_project;

use crate::{
    dev::BodyEncoding,
    service::{ServiceRequest, ServiceResponse},
    Error, HttpResponse,
};

/// Middleware for compressing response payloads.
///
/// Use `BodyEncoding` trait for overriding response compression. To disable compression set
/// encoding to `ContentEncoding::Identity`.
///
/// # Examples
/// ```
/// use actix_web::{web, middleware, App, HttpResponse};
///
/// let app = App::new()
///     .wrap(middleware::Compress::default())
///     .default_service(web::to(|| HttpResponse::NotFound()));
/// ```
#[derive(Debug, Clone)]
pub struct Compress(ContentEncoding);

impl Compress {
    /// Create new `Compress` middleware with the specified encoding.
    pub fn new(encoding: ContentEncoding) -> Self {
        Compress(encoding)
    }
}

impl Default for Compress {
    fn default() -> Self {
        Compress::new(ContentEncoding::Auto)
    }
}

impl<S, B> Transform<S, ServiceRequest> for Compress
where
    B: MessageBody,
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
    type Response = ServiceResponse<EitherBody<Encoder<B>>>;
    type Error = Error;
    type Transform = CompressMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(CompressMiddleware {
            service,
            encoding: self.0,
        })
    }
}

pub struct CompressMiddleware<S> {
    service: S,
    encoding: ContentEncoding,
}

static SUPPORTED_ALGORITHM_NAMES: Lazy<String> = Lazy::new(|| {
    #[allow(unused_mut)] // only unused when no compress features enabled
    let mut encoding: Vec<&str> = vec![];

    #[cfg(feature = "compress-brotli")]
    {
        encoding.push("br");
    }

    #[cfg(feature = "compress-gzip")]
    {
        encoding.push("gzip");
        encoding.push("deflate");
    }

    #[cfg(feature = "compress-zstd")]
    encoding.push("zstd");

    assert!(
        !encoding.is_empty(),
        "encoding can not be empty unless __compress feature has been explicitly enabled by itself"
    );

    encoding.join(", ")
});

impl<S, B> Service<ServiceRequest> for CompressMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
{
    type Response = ServiceResponse<EitherBody<Encoder<B>>>;
    type Error = Error;
    #[allow(clippy::type_complexity)]
    type Future = Either<CompressResponse<S, B>, Ready<Result<Self::Response, Self::Error>>>;

    actix_service::forward_ready!(service);

    #[allow(clippy::borrow_interior_mutable_const)]
    fn call(&self, req: ServiceRequest) -> Self::Future {
        // negotiate content-encoding
        let encoding_result = req
            .headers()
            .get(&ACCEPT_ENCODING)
            .and_then(|val| val.to_str().ok())
            .map(|enc| AcceptEncoding::try_parse(enc, self.encoding));

        match encoding_result {
            // Missing header => fallback to identity
            None => Either::left(CompressResponse {
                encoding: ContentEncoding::Identity,
                fut: self.service.call(req),
                _phantom: PhantomData,
            }),

            // Valid encoding
            Some(Ok(encoding)) => Either::left(CompressResponse {
                encoding,
                fut: self.service.call(req),
                _phantom: PhantomData,
            }),

            // There is an HTTP header but we cannot match what client as asked for
            Some(Err(_)) => {
                let res = HttpResponse::with_body(
                    StatusCode::NOT_ACCEPTABLE,
                    SUPPORTED_ALGORITHM_NAMES.clone(),
                );

                Either::right(ok(req
                    .into_response(res)
                    .map_into_boxed_body()
                    .map_into_right_body()))
            }
        }
    }
}

pin_project! {
    pub struct CompressResponse<S, B>
    where
        S: Service<ServiceRequest>,
    {
        #[pin]
        fut: S::Future,
        encoding: ContentEncoding,
        _phantom: PhantomData<B>,
    }
}

impl<S, B> Future for CompressResponse<S, B>
where
    B: MessageBody,
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
    type Output = Result<ServiceResponse<EitherBody<Encoder<B>>>, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();

        match ready!(this.fut.poll(cx)) {
            Ok(resp) => {
                let enc = if let Some(enc) = resp.response().get_encoding() {
                    enc
                } else {
                    *this.encoding
                };

                Poll::Ready(Ok(resp.map_body(move |head, body| {
                    EitherBody::left(Encoder::response(enc, head, body))
                })))
            }

            Err(err) => Poll::Ready(Err(err)),
        }
    }
}

struct AcceptEncoding {
    encoding: ContentEncoding,
    // TODO: use Quality or QualityItem<ContentEncoding>
    quality: f64,
}

impl Eq for AcceptEncoding {}

impl Ord for AcceptEncoding {
    #[allow(clippy::comparison_chain)]
    fn cmp(&self, other: &AcceptEncoding) -> cmp::Ordering {
        if self.quality > other.quality {
            cmp::Ordering::Less
        } else if self.quality < other.quality {
            cmp::Ordering::Greater
        } else {
            cmp::Ordering::Equal
        }
    }
}

impl PartialOrd for AcceptEncoding {
    fn partial_cmp(&self, other: &AcceptEncoding) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for AcceptEncoding {
    fn eq(&self, other: &AcceptEncoding) -> bool {
        self.encoding == other.encoding && self.quality == other.quality
    }
}

/// Parse q-factor from quality strings.
///
/// If parse fail, then fallback to default value which is 1.
/// More details available here: <https://developer.mozilla.org/en-US/docs/Glossary/Quality_values>
fn parse_quality(parts: &[&str]) -> f64 {
    for part in parts {
        if part.trim().starts_with("q=") {
            return part[2..].parse().unwrap_or(1.0);
        }
    }

    1.0
}

#[derive(Debug, PartialEq, Eq)]
enum AcceptEncodingError {
    /// This error occurs when client only support compressed response and server do not have any
    /// algorithm that match client accepted algorithms.
    CompressionAlgorithmMismatch,
}

impl AcceptEncoding {
    fn new(tag: &str) -> Option<AcceptEncoding> {
        let parts: Vec<&str> = tag.split(';').collect();
        let encoding = match parts.len() {
            0 => return None,
            _ => match ContentEncoding::try_from(parts[0]) {
                Err(_) => return None,
                Ok(x) => x,
            },
        };

        let quality = parse_quality(&parts[1..]);
        if quality <= 0.0 || quality > 1.0 {
            return None;
        }

        Some(AcceptEncoding { encoding, quality })
    }

    /// Parse a raw Accept-Encoding header value into an ordered list then return the best match
    /// based on middleware configuration.
    pub fn try_parse(
        raw: &str,
        encoding: ContentEncoding,
    ) -> Result<ContentEncoding, AcceptEncodingError> {
        let mut encodings = raw
            .replace(' ', "")
            .split(',')
            .filter_map(AcceptEncoding::new)
            .collect::<Vec<_>>();

        encodings.sort();

        for enc in encodings {
            if encoding == ContentEncoding::Auto || encoding == enc.encoding {
                return Ok(enc.encoding);
            }
        }

        // Special case if user cannot accept uncompressed data.
        // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
        // TODO: account for whitespace
        if raw.contains("*;q=0") || raw.contains("identity;q=0") {
            return Err(AcceptEncodingError::CompressionAlgorithmMismatch);
        }

        Ok(ContentEncoding::Identity)
    }
}

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

    macro_rules! assert_parse_eq {
        ($raw:expr, $result:expr) => {
            assert_eq!(
                AcceptEncoding::try_parse($raw, ContentEncoding::Auto),
                Ok($result)
            );
        };
    }

    macro_rules! assert_parse_fail {
        ($raw:expr) => {
            assert!(AcceptEncoding::try_parse($raw, ContentEncoding::Auto).is_err());
        };
    }

    #[test]
    fn test_parse_encoding() {
        // Test simple case
        assert_parse_eq!("br", ContentEncoding::Br);
        assert_parse_eq!("gzip", ContentEncoding::Gzip);
        assert_parse_eq!("deflate", ContentEncoding::Deflate);
        assert_parse_eq!("zstd", ContentEncoding::Zstd);

        // Test space, trim, missing values
        assert_parse_eq!("br,,,,", ContentEncoding::Br);
        assert_parse_eq!("gzip  ,   br,   zstd", ContentEncoding::Gzip);

        // Test float number parsing
        assert_parse_eq!("br;q=1  ,", ContentEncoding::Br);
        assert_parse_eq!("br;q=1.0  ,   br", ContentEncoding::Br);

        // Test wildcard
        assert_parse_eq!("*", ContentEncoding::Identity);
        assert_parse_eq!("*;q=1.0", ContentEncoding::Identity);
    }

    #[test]
    fn test_parse_encoding_qfactor_ordering() {
        assert_parse_eq!("gzip, br, zstd", ContentEncoding::Gzip);
        assert_parse_eq!("zstd, br, gzip", ContentEncoding::Zstd);

        assert_parse_eq!("gzip;q=0.4, br;q=0.6", ContentEncoding::Br);
        assert_parse_eq!("gzip;q=0.8, br;q=0.4", ContentEncoding::Gzip);
    }

    #[test]
    fn test_parse_encoding_qfactor_invalid() {
        // Out of range
        assert_parse_eq!("gzip;q=-5.0", ContentEncoding::Identity);
        assert_parse_eq!("gzip;q=5.0", ContentEncoding::Identity);

        // Disabled
        assert_parse_eq!("gzip;q=0", ContentEncoding::Identity);
    }

    #[test]
    fn test_parse_compression_required() {
        // Check we fallback to identity if there is an unsupported compression algorithm
        assert_parse_eq!("compress", ContentEncoding::Identity);

        // User do not want any compression
        assert_parse_fail!("compress, identity;q=0");
        assert_parse_fail!("compress, identity;q=0.0");
        assert_parse_fail!("compress, *;q=0");
        assert_parse_fail!("compress, *;q=0.0");
    }
}