Add zlib-specific codec initialization
[folly.git] / folly / io / compression / Zlib.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/io/compression/Zlib.h>
18
19 #if FOLLY_HAVE_LIBZ
20
21 #include <folly/Conv.h>
22 #include <folly/Optional.h>
23 #include <folly/Range.h>
24 #include <folly/ScopeGuard.h>
25 #include <folly/io/Compression.h>
26 #include <folly/io/Cursor.h>
27 #include <folly/io/compression/Utils.h>
28
29 using folly::io::compression::detail::dataStartsWithLE;
30 using folly::io::compression::detail::prefixToStringLE;
31
32 namespace folly {
33 namespace io {
34 namespace zlib {
35
36 namespace {
37
38 bool isValidStrategy(int strategy) {
39   std::array<int, 5> strategies{{
40       Z_DEFAULT_STRATEGY,
41       Z_FILTERED,
42       Z_HUFFMAN_ONLY,
43       Z_RLE,
44       Z_FIXED
45   }};
46   return std::any_of(strategies.begin(), strategies.end(), [&](int i) {
47     return i == strategy;
48   });
49 }
50
51 int getWindowBits(Options::Format format, int windowSize) {
52   switch (format) {
53     case Options::Format::ZLIB:
54       return windowSize;
55     case Options::Format::GZIP:
56       return windowSize + 16;
57     case Options::Format::RAW:
58       return -windowSize;
59     case Options::Format::AUTO:
60       return windowSize + 32;
61     default:
62       return windowSize;
63   }
64 }
65
66 CodecType getCodecType(Options options) {
67   if (options.windowSize == 15 && options.format == Options::Format::ZLIB) {
68     return CodecType::ZLIB;
69   } else if (
70       options.windowSize == 15 && options.format == Options::Format::GZIP) {
71     return CodecType::GZIP;
72   } else {
73     return CodecType::USER_DEFINED;
74   }
75 }
76
77 class ZlibStreamCodec final : public StreamCodec {
78  public:
79   static std::unique_ptr<Codec> createCodec(Options options, int level);
80   static std::unique_ptr<StreamCodec> createStream(Options options, int level);
81
82   explicit ZlibStreamCodec(Options options, int level);
83   ~ZlibStreamCodec() override;
84
85   std::vector<std::string> validPrefixes() const override;
86   bool canUncompress(const IOBuf* data, Optional<uint64_t> uncompressedLength)
87       const override;
88
89  private:
90   uint64_t doMaxCompressedLength(uint64_t uncompressedLength) const override;
91
92   void doResetStream() override;
93   bool doCompressStream(
94       ByteRange& input,
95       MutableByteRange& output,
96       StreamCodec::FlushOp flush) override;
97   bool doUncompressStream(
98       ByteRange& input,
99       MutableByteRange& output,
100       StreamCodec::FlushOp flush) override;
101
102   void resetDeflateStream();
103   void resetInflateStream();
104
105   Options options_;
106
107   Optional<z_stream> deflateStream_{};
108   Optional<z_stream> inflateStream_{};
109   int level_;
110   bool needReset_{true};
111 };
112 static constexpr uint16_t kGZIPMagicLE = 0x8B1F;
113
114 std::vector<std::string> ZlibStreamCodec::validPrefixes() const {
115   if (type() == CodecType::ZLIB) {
116     // Zlib streams start with a 2 byte header.
117     //
118     //   0   1
119     // +---+---+
120     // |CMF|FLG|
121     // +---+---+
122     //
123     // We won't restrict the values of any sub-fields except as described below.
124     //
125     // The lowest 4 bits of CMF is the compression method (CM).
126     // CM == 0x8 is the deflate compression method, which is currently the only
127     // supported compression method, so any valid prefix must have CM == 0x8.
128     //
129     // The lowest 5 bits of FLG is FCHECK.
130     // FCHECK must be such that the two header bytes are a multiple of 31 when
131     // interpreted as a big endian 16-bit number.
132     std::vector<std::string> result;
133     // 16 values for the first byte, 8 values for the second byte.
134     // There are also 4 combinations where both 0x00 and 0x1F work as FCHECK.
135     result.reserve(132);
136     // Select all values for the CMF byte that use the deflate algorithm 0x8.
137     for (uint32_t first = 0x0800; first <= 0xF800; first += 0x1000) {
138       // Select all values for the FLG, but leave FCHECK as 0 since it's fixed.
139       for (uint32_t second = 0x00; second <= 0xE0; second += 0x20) {
140         uint16_t prefix = first | second;
141         // Compute FCHECK.
142         prefix += 31 - (prefix % 31);
143         result.push_back(prefixToStringLE(Endian::big(prefix)));
144         // zlib won't produce this, but it is a valid prefix.
145         if ((prefix & 0x1F) == 31) {
146           prefix -= 31;
147           result.push_back(prefixToStringLE(Endian::big(prefix)));
148         }
149       }
150     }
151     return result;
152   } else if (type() == CodecType::GZIP) {
153     // The gzip frame starts with 2 magic bytes.
154     return {prefixToStringLE(kGZIPMagicLE)};
155   } else {
156     return {};
157   }
158 }
159
160 bool ZlibStreamCodec::canUncompress(const IOBuf* data, Optional<uint64_t>)
161     const {
162   if (type() == CodecType::ZLIB) {
163     uint16_t value;
164     Cursor cursor{data};
165     if (!cursor.tryReadBE(value)) {
166       return false;
167     }
168     // zlib compressed if using deflate and is a multiple of 31.
169     return (value & 0x0F00) == 0x0800 && value % 31 == 0;
170   } else if (type() == CodecType::GZIP) {
171     return dataStartsWithLE(data, kGZIPMagicLE);
172   } else {
173     return false;
174   }
175 }
176
177 uint64_t ZlibStreamCodec::doMaxCompressedLength(
178     uint64_t uncompressedLength) const {
179   return deflateBound(nullptr, uncompressedLength);
180 }
181
182 std::unique_ptr<Codec> ZlibStreamCodec::createCodec(
183     Options options,
184     int level) {
185   return std::make_unique<ZlibStreamCodec>(options, level);
186 }
187
188 std::unique_ptr<StreamCodec> ZlibStreamCodec::createStream(
189     Options options,
190     int level) {
191   return std::make_unique<ZlibStreamCodec>(options, level);
192 }
193
194 ZlibStreamCodec::ZlibStreamCodec(Options options, int level)
195     : StreamCodec(getCodecType(options)) {
196   switch (level) {
197     case COMPRESSION_LEVEL_FASTEST:
198       level = 1;
199       break;
200     case COMPRESSION_LEVEL_DEFAULT:
201       level = Z_DEFAULT_COMPRESSION;
202       break;
203     case COMPRESSION_LEVEL_BEST:
204       level = 9;
205       break;
206   }
207   auto inBounds = [](int value, int low, int high) {
208     return (value >= low) && (value <= high);
209   };
210
211   if (level != Z_DEFAULT_COMPRESSION && !inBounds(level, 0, 9)) {
212     throw std::invalid_argument(
213         to<std::string>("ZlibStreamCodec: invalid level: ", level));
214   }
215   level_ = level;
216   options_ = options;
217
218   // Although zlib allows a windowSize of 8..15, a value of 8 is not
219   // properly supported and is treated as a value of 9. This means data deflated
220   // with windowSize==8 can not be re-inflated with windowSize==8. windowSize==8
221   // is also not supported for gzip and raw deflation.
222   // Hence, the codec supports only 9..15.
223   if (!inBounds(options_.windowSize, 9, 15)) {
224     throw std::invalid_argument(to<std::string>(
225         "ZlibStreamCodec: invalid windowSize option: ", options.windowSize));
226   }
227   if (!inBounds(options_.memLevel, 1, 9)) {
228     throw std::invalid_argument(to<std::string>(
229         "ZlibStreamCodec: invalid memLevel option: ", options.memLevel));
230   }
231   if (!isValidStrategy(options_.strategy)) {
232     throw std::invalid_argument(to<std::string>(
233         "ZlibStreamCodec: invalid strategy: ", options.strategy));
234   }
235 }
236
237 ZlibStreamCodec::~ZlibStreamCodec() {
238   if (deflateStream_) {
239     deflateEnd(deflateStream_.get_pointer());
240     deflateStream_.clear();
241   }
242   if (inflateStream_) {
243     inflateEnd(inflateStream_.get_pointer());
244     inflateStream_.clear();
245   }
246 }
247
248 void ZlibStreamCodec::doResetStream() {
249   needReset_ = true;
250 }
251
252 void ZlibStreamCodec::resetDeflateStream() {
253   if (deflateStream_) {
254     int const rc = deflateReset(deflateStream_.get_pointer());
255     if (rc != Z_OK) {
256       deflateStream_.clear();
257       throw std::runtime_error(
258           to<std::string>("ZlibStreamCodec: deflateReset error: ", rc));
259     }
260     return;
261   }
262   deflateStream_ = z_stream{};
263
264   // The automatic header detection format is only for inflation.
265   // Use zlib for deflation if the format is auto.
266   int const windowBits = getWindowBits(
267       options_.format == Options::Format::AUTO ? Options::Format::ZLIB
268                                                : options_.format,
269       options_.windowSize);
270
271   int const rc = deflateInit2(
272       deflateStream_.get_pointer(),
273       level_,
274       Z_DEFLATED,
275       windowBits,
276       options_.memLevel,
277       options_.strategy);
278   if (rc != Z_OK) {
279     deflateStream_.clear();
280     throw std::runtime_error(
281         to<std::string>("ZlibStreamCodec: deflateInit error: ", rc));
282   }
283 }
284
285 void ZlibStreamCodec::resetInflateStream() {
286   if (inflateStream_) {
287     int const rc = inflateReset(inflateStream_.get_pointer());
288     if (rc != Z_OK) {
289       inflateStream_.clear();
290       throw std::runtime_error(
291           to<std::string>("ZlibStreamCodec: inflateReset error: ", rc));
292     }
293     return;
294   }
295   inflateStream_ = z_stream{};
296   int const rc = inflateInit2(
297       inflateStream_.get_pointer(),
298       getWindowBits(options_.format, options_.windowSize));
299   if (rc != Z_OK) {
300     inflateStream_.clear();
301     throw std::runtime_error(
302         to<std::string>("ZlibStreamCodec: inflateInit error: ", rc));
303   }
304 }
305
306 static int zlibTranslateFlush(StreamCodec::FlushOp flush) {
307   switch (flush) {
308     case StreamCodec::FlushOp::NONE:
309       return Z_NO_FLUSH;
310     case StreamCodec::FlushOp::FLUSH:
311       return Z_SYNC_FLUSH;
312     case StreamCodec::FlushOp::END:
313       return Z_FINISH;
314     default:
315       throw std::invalid_argument("ZlibStreamCodec: Invalid flush");
316   }
317 }
318
319 static int zlibThrowOnError(int rc) {
320   switch (rc) {
321     case Z_OK:
322     case Z_BUF_ERROR:
323     case Z_STREAM_END:
324       return rc;
325     default:
326       throw std::runtime_error(to<std::string>("ZlibStreamCodec: error: ", rc));
327   }
328 }
329
330 bool ZlibStreamCodec::doCompressStream(
331     ByteRange& input,
332     MutableByteRange& output,
333     StreamCodec::FlushOp flush) {
334   if (needReset_) {
335     resetDeflateStream();
336     needReset_ = false;
337   }
338   DCHECK(deflateStream_.hasValue());
339   // zlib will return Z_STREAM_ERROR if output.data() is null.
340   if (output.data() == nullptr) {
341     return false;
342   }
343   deflateStream_->next_in = const_cast<uint8_t*>(input.data());
344   deflateStream_->avail_in = input.size();
345   deflateStream_->next_out = output.data();
346   deflateStream_->avail_out = output.size();
347   SCOPE_EXIT {
348     input.uncheckedAdvance(input.size() - deflateStream_->avail_in);
349     output.uncheckedAdvance(output.size() - deflateStream_->avail_out);
350   };
351   int const rc = zlibThrowOnError(
352       deflate(deflateStream_.get_pointer(), zlibTranslateFlush(flush)));
353   switch (flush) {
354     case StreamCodec::FlushOp::NONE:
355       return false;
356     case StreamCodec::FlushOp::FLUSH:
357       return deflateStream_->avail_in == 0 && deflateStream_->avail_out != 0;
358     case StreamCodec::FlushOp::END:
359       return rc == Z_STREAM_END;
360     default:
361       throw std::invalid_argument("ZlibStreamCodec: Invalid flush");
362   }
363 }
364
365 bool ZlibStreamCodec::doUncompressStream(
366     ByteRange& input,
367     MutableByteRange& output,
368     StreamCodec::FlushOp flush) {
369   if (needReset_) {
370     resetInflateStream();
371     needReset_ = false;
372   }
373   DCHECK(inflateStream_.hasValue());
374   // zlib will return Z_STREAM_ERROR if output.data() is null.
375   if (output.data() == nullptr) {
376     return false;
377   }
378   inflateStream_->next_in = const_cast<uint8_t*>(input.data());
379   inflateStream_->avail_in = input.size();
380   inflateStream_->next_out = output.data();
381   inflateStream_->avail_out = output.size();
382   SCOPE_EXIT {
383     input.advance(input.size() - inflateStream_->avail_in);
384     output.advance(output.size() - inflateStream_->avail_out);
385   };
386   int const rc = zlibThrowOnError(
387       inflate(inflateStream_.get_pointer(), zlibTranslateFlush(flush)));
388   return rc == Z_STREAM_END;
389 }
390
391 } // namespace
392
393 Options defaultGzipOptions() {
394   return Options(Options::Format::GZIP);
395 }
396
397 Options defaultZlibOptions() {
398   return Options(Options::Format::ZLIB);
399 }
400
401 std::unique_ptr<Codec> getCodec(Options options, int level) {
402   return ZlibStreamCodec::createCodec(options, level);
403 }
404
405 std::unique_ptr<StreamCodec> getStreamCodec(Options options, int level) {
406   return ZlibStreamCodec::createStream(options, level);
407 }
408
409 } // namespace zlib
410 } // namespace io
411 } // namespace folly
412
413 #endif // FOLLY_HAVE_LIBZ