Skip to main content

utopia_compression/
zlib.rs

1//! Deflate and GZIP on zlib, called exactly as PHP's ext-zlib calls it.
2
3use crate::{Algorithm, Compression, Error, Sink};
4
5/// Raw deflate (RFC 1951) at level 6: `Content-Encoding: deflate`.
6///
7/// Output is byte for byte PHP's `gzdeflate($data, 6)`: the system's zlib (the one PHP links)
8/// at memory level 9. Decompressing accepts what `gzinflate()` accepts, including trailing
9/// bytes after the stream, which are ignored.
10///
11/// ```
12/// use utopia_compression::{Algorithm, Deflate};
13///
14/// let deflate = Deflate::new();
15/// assert_eq!(deflate.compress(b"a")?, b"\x4b\x04\x00");
16/// assert_eq!(deflate.decompress(b"\x4b\x04\x00")?, b"a");
17/// # Ok::<(), utopia_compression::Error>(())
18/// ```
19///
20/// ```php
21/// use Utopia\Compression\Algorithms\Deflate;
22///
23/// $deflate = new Deflate();
24/// echo bin2hex($deflate->compress('a')), "\n"; // 4b0400
25/// echo $deflate->decompress("\x4b\x04\x00"), "\n"; // a
26/// ```
27///
28/// Requires the `zlib` feature. PHP: `Utopia\Compression\Algorithms\Deflate`.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub struct Deflate;
31
32impl Deflate {
33    /// Raw deflate at level 6.
34    ///
35    /// PHP: `new Deflate()`.
36    pub const fn new() -> Self {
37        Deflate
38    }
39
40    /// Whether this build has zlib (the `zlib` feature).
41    ///
42    /// PHP: `Deflate::isSupported()`, whether `gzdeflate()` exists.
43    pub const fn is_supported() -> bool {
44        cfg!(feature = "zlib")
45    }
46
47    /// [`Algorithm::compress`], appended to `out`.
48    pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
49        imp::encode(data, 6, imp::RAW, "gzdeflate", out)
50    }
51
52    /// [`Algorithm::decompress`], appended to `out`.
53    pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
54        imp::decode(data, imp::RAW, "gzinflate", out)
55    }
56}
57
58impl Algorithm for Deflate {
59    fn name(&self) -> &str {
60        Compression::DEFLATE
61    }
62
63    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
64        let mut out = Vec::new();
65        self.compress_into(data, &mut out)?;
66        Ok(out)
67    }
68
69    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
70        let mut out = Vec::new();
71        self.decompress_into(data, &mut out)?;
72        Ok(out)
73    }
74
75    fn supported(&self) -> bool {
76        Self::is_supported()
77    }
78}
79
80/// Gzip (RFC 1952) at zlib's default level: `Content-Encoding: gzip`.
81///
82/// Output is byte for byte PHP's `gzencode($data)`: a header with no name, a modification
83/// time of 0 and the Unix OS byte (3), then the system zlib's deflate at level 6 and memory
84/// level 9. Decompressing reads the first member, like `gzdecode()`.
85///
86/// ```
87/// use utopia_compression::{Algorithm, Gzip};
88///
89/// let gzip = Gzip::new();
90/// let body = gzip.compress(b"a")?;
91/// assert_eq!(&body[..10], b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03");
92/// assert_eq!(gzip.decompress(&body)?, b"a");
93/// # Ok::<(), utopia_compression::Error>(())
94/// ```
95///
96/// ```php
97/// use Utopia\Compression\Algorithms\GZIP;
98///
99/// $gzip = new GZIP();
100/// $body = $gzip->compress('a');
101/// echo bin2hex(substr($body, 0, 10)), "\n"; // 1f8b0800000000000003
102/// echo $gzip->decompress($body), "\n"; // a
103/// ```
104///
105/// Requires the `zlib` feature. PHP: `Utopia\Compression\Algorithms\GZIP`.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
107pub struct Gzip;
108
109impl Gzip {
110    /// Gzip at zlib's default level.
111    ///
112    /// PHP: `new GZIP()`.
113    pub const fn new() -> Self {
114        Gzip
115    }
116
117    /// Whether this build has zlib (the `zlib` feature).
118    ///
119    /// PHP: `GZIP::isSupported()`, whether `gzencode()` exists.
120    pub const fn is_supported() -> bool {
121        cfg!(feature = "zlib")
122    }
123
124    /// [`Algorithm::compress`], appended to `out`.
125    pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
126        imp::encode(data, -1, imp::GZIP, "gzencode", out)
127    }
128
129    /// [`Algorithm::decompress`], appended to `out`.
130    pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
131        imp::decode(data, imp::GZIP, "gzdecode", out)
132    }
133}
134
135impl Algorithm for Gzip {
136    fn name(&self) -> &str {
137        Compression::GZIP
138    }
139
140    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
141        let mut out = Vec::new();
142        self.compress_into(data, &mut out)?;
143        Ok(out)
144    }
145
146    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
147        let mut out = Vec::new();
148        self.decompress_into(data, &mut out)?;
149        Ok(out)
150    }
151
152    fn supported(&self) -> bool {
153        Self::is_supported()
154    }
155}
156
157#[cfg(feature = "zlib")]
158mod imp {
159    //! The zlib calls of PHP's `php_zlib_encode()` and `php_zlib_decode()` (ext/zlib/zlib.c),
160    //! with the same buffer sizes, writing straight into the sink.
161    //!
162    //! zlib's deflate at memory level 9 is what PHP writes, and no safe binding exposes the
163    //! memory level (flate2 hardcodes 8, which changes the output). A stream lives boxed in a
164    //! `MaybeUninit` that is only ever handed to zlib by pointer, so the null allocator
165    //! pointers zlib expects (to use its defaults) never become a Rust value; zlib keeps a
166    //! pointer back to it, so it never moves.
167    //!
168    //! PHP sets up a stream for every call (about 330 KiB of state for deflate, all of it
169    //! allocated and initialised again). Here each thread keeps one stream of each kind and
170    //! resets it, which zlib defines as the state `deflateInit2()` leaves: the output is the
171    //! same.
172
173    use std::cell::Cell;
174    use std::mem::MaybeUninit;
175    use std::os::raw::c_int;
176    use std::thread::LocalKey;
177
178    use libz_sys as z;
179
180    use crate::sink::spare;
181    use crate::{Error, Sink};
182
183    /// `ZLIB_ENCODING_RAW`: raw deflate, no header.
184    pub(super) const RAW: c_int = -15;
185    /// `ZLIB_ENCODING_GZIP`: a gzip header and trailer.
186    pub(super) const GZIP: c_int = 31;
187
188    /// The terminating NUL of a PHP string, which PHP passes to inflate.
189    static NUL: [u8; 1] = [0];
190
191    /// `MAX_MEM_LEVEL`, the memory level PHP deflates with.
192    const MEM_LEVEL: c_int = 9;
193
194    /// The most deflate expands: 1,032 output bytes per input byte (a run of 258 in under two
195    /// bits), so a gzip trailer claiming more is not believed.
196    const MAX_RATIO: usize = 1032;
197
198    /// zlib's `zError()`.
199    fn message(status: c_int) -> &'static str {
200        match status {
201            z::Z_NEED_DICT => "need dictionary",
202            z::Z_STREAM_END => "stream end",
203            z::Z_ERRNO => "file error",
204            z::Z_STREAM_ERROR => "stream error",
205            z::Z_DATA_ERROR => "data error",
206            z::Z_MEM_ERROR => "insufficient memory",
207            z::Z_BUF_ERROR => "buffer error",
208            z::Z_VERSION_ERROR => "incompatible version",
209            _ => "",
210        }
211    }
212
213    /// PHP's warning: `gzinflate(): data error`.
214    fn codec(function: &str, status: c_int) -> Error {
215        Error::Codec(format!("{function}(): {}", message(status)))
216    }
217
218    /// A deflate or inflate stream of zlib, set up for one encoding.
219    struct Stream {
220        raw: Box<MaybeUninit<z::z_stream>>,
221        inflate: bool,
222    }
223
224    impl Stream {
225        fn ptr(&mut self) -> *mut z::z_stream {
226            self.raw.as_mut_ptr()
227        }
228    }
229
230    impl Drop for Stream {
231        fn drop(&mut self) {
232            let s = self.ptr();
233            // SAFETY: a stream is only built once deflateInit2_ or inflateInit2_ succeeded; the
234            // matching End frees its state.
235            unsafe {
236                if self.inflate {
237                    z::inflateEnd(s);
238                } else {
239                    z::deflateEnd(s);
240                }
241            }
242        }
243    }
244
245    thread_local! {
246        static DEFLATE_RAW: Cell<Option<Stream>> = const { Cell::new(None) };
247        static DEFLATE_GZIP: Cell<Option<Stream>> = const { Cell::new(None) };
248        static INFLATE_RAW: Cell<Option<Stream>> = const { Cell::new(None) };
249        static INFLATE_GZIP: Cell<Option<Stream>> = const { Cell::new(None) };
250    }
251
252    /// The thread's slot for the stream of `encoding`. A stream is taken out of it while in
253    /// use, so a call that never puts it back (one PHP abandons on a fatal error) only leaves
254    /// the next call to set up a new one.
255    fn slot(inflate: bool, encoding: c_int) -> &'static LocalKey<Cell<Option<Stream>>> {
256        match (inflate, encoding == GZIP) {
257            (false, false) => &DEFLATE_RAW,
258            (false, true) => &DEFLATE_GZIP,
259            (true, false) => &INFLATE_RAW,
260            (true, true) => &INFLATE_GZIP,
261        }
262    }
263
264    /// A deflate stream at `level` for `encoding`, as `deflateInit2()` leaves it. Each
265    /// encoding is only ever deflated at one level, so a kept stream already has it.
266    fn deflater(level: c_int, encoding: c_int) -> Result<Stream, c_int> {
267        if let Some(mut stream) = slot(false, encoding).with(Cell::take) {
268            // SAFETY: an initialised deflate stream.
269            if unsafe { z::deflateReset(stream.ptr()) } == z::Z_OK {
270                return Ok(stream);
271            }
272        }
273        let mut raw = Box::new(MaybeUninit::<z::z_stream>::zeroed());
274        // SAFETY: a zeroed z_stream, which deflateInit2_ initialises (null zalloc/zfree/opaque
275        // select zlib's allocator).
276        let status = unsafe {
277            z::deflateInit2_(
278                raw.as_mut_ptr(),
279                level,
280                z::Z_DEFLATED,
281                encoding,
282                MEM_LEVEL,
283                z::Z_DEFAULT_STRATEGY,
284                z::zlibVersion(),
285                std::mem::size_of::<z::z_stream>() as c_int,
286            )
287        };
288        if status != z::Z_OK {
289            return Err(status);
290        }
291        Ok(Stream { raw, inflate: false })
292    }
293
294    /// An inflate stream for `encoding`, as `inflateInit2()` leaves it.
295    fn inflater(encoding: c_int) -> Result<Stream, c_int> {
296        if let Some(mut stream) = slot(true, encoding).with(Cell::take) {
297            // SAFETY: an initialised inflate stream.
298            if unsafe { z::inflateReset(stream.ptr()) } == z::Z_OK {
299                return Ok(stream);
300            }
301        }
302        let mut raw = Box::new(MaybeUninit::<z::z_stream>::zeroed());
303        // SAFETY: as in `deflater`.
304        let status = unsafe {
305            z::inflateInit2_(raw.as_mut_ptr(), encoding, z::zlibVersion(), std::mem::size_of::<z::z_stream>() as c_int)
306        };
307        if status != z::Z_OK {
308            return Err(status);
309        }
310        Ok(Stream { raw, inflate: true })
311    }
312
313    /// Puts `stream` back for the thread's next call.
314    fn keep(stream: Stream, encoding: c_int) {
315        slot(stream.inflate, encoding).with(|slot| slot.set(Some(stream)));
316    }
317
318    /// `php_zlib_encode()`: one `deflate(Z_FINISH)` into a buffer of
319    /// `PHP_ZLIB_BUFFER_SIZE_GUESS(len)` bytes.
320    pub(super) fn encode<S: Sink + ?Sized>(
321        data: &[u8],
322        level: c_int,
323        encoding: c_int,
324        function: &str,
325        out: &mut S,
326    ) -> Result<(), Error> {
327        let start = out.len();
328        let guess = (data.len() as f64 * 1.015) as usize + 10 + 8 + 4 + 1;
329        // The output is allocated before the stream is taken, as PHP allocates it.
330        if !out.grow(start + guess) {
331            return Err(codec(function, z::Z_MEM_ERROR));
332        }
333        let mut stream = deflater(level, encoding).map_err(|status| codec(function, status))?;
334        let (at, _) = spare(out);
335        let s = stream.ptr();
336        // SAFETY: the stream is initialised; next_in covers `data` (zlib only reads it) and
337        // next_out the `guess` bytes of room made in `out`; both outlive the call. PHP hands
338        // zlib its sizes as `uInt`, truncating them the same way.
339        let (status, written) = unsafe {
340            (&raw mut (*s).next_in).write(data.as_ptr().cast_mut());
341            (&raw mut (*s).avail_in).write(data.len() as z::uInt);
342            (&raw mut (*s).next_out).write(at);
343            (&raw mut (*s).avail_out).write(guess as z::uInt);
344            let status = z::deflate(s, z::Z_FINISH);
345            (status, (&raw const (*s).total_out).read() as usize)
346        };
347        keep(stream, encoding);
348        if status != z::Z_STREAM_END {
349            return Err(codec(function, status));
350        }
351        // SAFETY: deflate wrote `written` bytes (at most `guess`) after the `start` held.
352        unsafe { out.set_len(start + written.min(guess)) };
353        // zlib writes the OS of the build into the gzip header (19 on macOS, 10 on Windows);
354        // PHP runs on Linux, which writes 3 (Unix).
355        if encoding == GZIP && written > 9 {
356            // SAFETY: byte 9 of the header was just written.
357            unsafe { *out.as_mut_ptr().add(start + 9) = 3 };
358        }
359        Ok(())
360    }
361
362    /// `php_zlib_decode()` and `php_zlib_inflate_rounds()`: the input with its terminating
363    /// NUL, inflated into a buffer that starts at the input's size and grows by an eighth, for
364    /// at most 100 rounds.
365    ///
366    /// Each round hands zlib PHP's buffer size, so the rounds, the output and the status are
367    /// PHP's. Only the allocation differs: a gzip trailer that gives the size reserves it at
368    /// once (then grows as PHP's does), and without one growing goes by halves rather than
369    /// eighths, so a large output is not copied again and again.
370    ///
371    /// PHP hands zlib the string's terminating NUL too. Rust feeds it as a second buffer once
372    /// the data is used up, within the same round: inflate streams, so the output and status
373    /// are those of one contiguous input.
374    pub(super) fn decode<S: Sink + ?Sized>(
375        data: &[u8],
376        encoding: c_int,
377        function: &str,
378        out: &mut S,
379    ) -> Result<(), Error> {
380        if data.is_empty() {
381            return Err(codec(function, z::Z_DATA_ERROR));
382        }
383        let start = out.len();
384        // ISIZE, the length of the member a gzip stream ends with: when it is believable, the
385        // whole output fits at once.
386        let mut hinted = false;
387        if encoding == GZIP
388            && data.len() >= 18
389            && let Some(trailer) = data.last_chunk::<4>()
390        {
391            let size = u32::from_le_bytes(*trailer) as usize;
392            if size <= data.len().saturating_mul(MAX_RATIO) {
393                hinted = out.reserve(start + size.max(data.len() + 1));
394            }
395        }
396        let mut stream = inflater(encoding).map_err(|status| codec(function, status))?;
397        let s = stream.ptr();
398        // SAFETY: the stream is initialised; next_in covers `data` or NUL and next_out the room
399        // made in `out` before each call; `used` only grows by what inflate reports writing, so
400        // set_len stays within what was written.
401        let status = unsafe {
402            (&raw mut (*s).next_in).write(data.as_ptr().cast_mut());
403            (&raw mut (*s).avail_in).write(data.len() as z::uInt);
404            let mut nul = true;
405            let feed_nul = |s: *mut z::z_stream| {
406                (&raw mut (*s).next_in).write(NUL.as_ptr().cast_mut());
407                (&raw mut (*s).avail_in).write(1);
408            };
409
410            let mut size = data.len() + 1;
411            let mut used = 0;
412            let mut round = 0;
413            loop {
414                // Within a trailer's size, a round gets the room left when PHP's would be larger:
415                // inflate streams, so it only stops sooner, and a full buffer gets another round
416                // (past the trailer's size, as PHP's buffer would have had room). Without one,
417                // growing goes by half, so a large output is copied less often.
418                let capacity = out.capacity();
419                let mut free = (size - used) as z::uInt;
420                let mut capped = false;
421                if start + size > capacity {
422                    if hinted && capacity > start + used {
423                        free = (capacity - start - used) as z::uInt;
424                        capped = true;
425                    } else if !out.grow((start + size).max(capacity + capacity / 2)) {
426                        break z::Z_MEM_ERROR;
427                    }
428                }
429                let (at, _) = spare(out);
430                (&raw mut (*s).next_out).write(at);
431                (&raw mut (*s).avail_out).write(free);
432                if nul && (&raw const (*s).avail_in).read() == 0 {
433                    feed_nul(s);
434                    nul = false;
435                }
436                let mut status = z::inflate(s, z::Z_NO_FLUSH);
437                if nul
438                    && status == z::Z_OK
439                    && (&raw const (*s).avail_in).read() == 0
440                    && (&raw const (*s).avail_out).read() != 0
441                {
442                    feed_nul(s);
443                    nul = false;
444                    status = z::inflate(s, z::Z_NO_FLUSH);
445                }
446                used += (free - (&raw const (*s).avail_out).read()) as usize;
447                out.set_len(start + used);
448                if capped && (&raw const (*s).avail_out).read() == 0 && matches!(status, z::Z_OK | z::Z_BUF_ERROR) {
449                    hinted = false;
450                    continue;
451                }
452                size += (size >> 3) + 1;
453                round += 1;
454                let more =
455                    status == z::Z_BUF_ERROR || (status == z::Z_OK && ((&raw const (*s).avail_in).read() != 0 || nul));
456                if !(more && round < 100) {
457                    break status;
458                }
459            }
460        };
461        keep(stream, encoding);
462        match status {
463            z::Z_STREAM_END => Ok(()),
464            // zpipe.c's rule: a stream that stops early is a data error.
465            z::Z_OK => Err(codec(function, z::Z_DATA_ERROR)),
466            status => Err(codec(function, status)),
467        }
468    }
469}
470
471#[cfg(not(feature = "zlib"))]
472mod imp {
473    use crate::{Error, Sink};
474
475    pub(super) const RAW: i32 = -15;
476    pub(super) const GZIP: i32 = 31;
477
478    pub(super) fn encode<S: Sink + ?Sized>(_: &[u8], _: i32, _: i32, function: &str, _: &mut S) -> Result<(), Error> {
479        Err(Error::undefined(function))
480    }
481
482    pub(super) fn decode<S: Sink + ?Sized>(_: &[u8], _: i32, function: &str, _: &mut S) -> Result<(), Error> {
483        Err(Error::undefined(function))
484    }
485}
486
487#[cfg(all(test, feature = "zlib"))]
488mod tests {
489    use super::*;
490
491    #[test]
492    fn round_trips() {
493        let data = b"hello hello hello hello".repeat(100);
494        for algorithm in [&Deflate as &dyn Algorithm, &Gzip] {
495            let compressed = algorithm.compress(&data).unwrap();
496            assert!(compressed.len() < data.len());
497            assert_eq!(algorithm.decompress(&compressed).unwrap(), data);
498            // Again, on the thread's kept streams.
499            assert_eq!(algorithm.compress(&data).unwrap(), compressed);
500            assert_eq!(algorithm.decompress(&compressed).unwrap(), data);
501        }
502    }
503
504    #[test]
505    fn appends() {
506        let mut out = b"prefix".to_vec();
507        Gzip.compress_into(b"abc", &mut out).unwrap();
508        assert_eq!(&out[..6], b"prefix");
509        assert_eq!(out[6 + 9], 3);
510        let mut plain = b"x".to_vec();
511        Gzip.decompress_into(&out[6..], &mut plain).unwrap();
512        assert_eq!(plain, b"xabc");
513    }
514
515    #[test]
516    fn invalid_data() {
517        assert_eq!(Deflate.decompress(b""), Err(Error::Codec("gzinflate(): data error".into())));
518        assert_eq!(Gzip.decompress(b"garbage"), Err(Error::Codec("gzdecode(): data error".into())));
519        // The trailer's size is only a guess at the room needed: a wrong one still fails the
520        // member's check, and a right one leaves the output as it was.
521        let data = b"abc".repeat(1000);
522        let mut body = Gzip.compress(&data).unwrap();
523        assert_eq!(Gzip.decompress(&body).unwrap(), data);
524        let len = body.len();
525        body[len - 4..].copy_from_slice(&7u32.to_le_bytes());
526        assert_eq!(Gzip.decompress(&body), Err(Error::Codec("gzdecode(): data error".into())));
527    }
528}