1 // Copyright 2016 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/filter/filter_source_stream_test_util.h"
6
7 #include <cstring>
8
9 #include "base/bit_cast.h"
10 #include "base/check_op.h"
11 #include "third_party/zlib/zlib.h"
12
13 namespace net {
14
15 // Compress |source| with length |source_len|. Write output into |dest|, and
16 // output length into |dest_len|. If |gzip_framing| is true, header will be
17 // added.
CompressGzip(const char * source,size_t source_len,char * dest,size_t * dest_len,bool gzip_framing)18 void CompressGzip(const char* source,
19 size_t source_len,
20 char* dest,
21 size_t* dest_len,
22 bool gzip_framing) {
23 size_t dest_left = *dest_len;
24 z_stream zlib_stream;
25 memset(&zlib_stream, 0, sizeof(zlib_stream));
26 int code;
27 if (gzip_framing) {
28 const int kMemLevel = 8; // the default, see deflateInit2(3)
29 code = deflateInit2(&zlib_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
30 -MAX_WBITS, kMemLevel, Z_DEFAULT_STRATEGY);
31 } else {
32 code = deflateInit(&zlib_stream, Z_DEFAULT_COMPRESSION);
33 }
34 DCHECK_EQ(Z_OK, code);
35
36 // If compressing with gzip framing, prepend a gzip header. See RFC 1952 2.2
37 // and 2.3 for more information.
38 if (gzip_framing) {
39 const unsigned char gzip_header[] = {
40 0x1f,
41 0x8b, // magic number
42 0x08, // CM 0x08 == "deflate"
43 0x00, // FLG 0x00 == nothing
44 0x00, 0x00, 0x00,
45 0x00, // MTIME 0x00000000 == no mtime
46 0x00, // XFL 0x00 == nothing
47 0xff, // OS 0xff == unknown
48 };
49 DCHECK_GE(dest_left, sizeof(gzip_header));
50 memcpy(dest, gzip_header, sizeof(gzip_header));
51 dest += sizeof(gzip_header);
52 dest_left -= sizeof(gzip_header);
53 }
54
55 zlib_stream.next_in = base::bit_cast<Bytef*>(source);
56 zlib_stream.avail_in = source_len;
57 zlib_stream.next_out = base::bit_cast<Bytef*>(dest);
58 zlib_stream.avail_out = dest_left;
59
60 code = deflate(&zlib_stream, Z_FINISH);
61 DCHECK_EQ(Z_STREAM_END, code);
62 dest_left = zlib_stream.avail_out;
63
64 deflateEnd(&zlib_stream);
65 *dest_len -= dest_left;
66 }
67
68 } // namespace net
69