1 // Copyright 2013 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/websockets/websocket_deflater.h"
6
7 #include <string.h>
8
9 #include <algorithm>
10 #include <vector>
11 #include <zlib.h>
12
13 #include "base/check_op.h"
14 #include "base/containers/circular_deque.h"
15 #include "net/base/io_buffer.h"
16
17 namespace net {
18
WebSocketDeflater(ContextTakeOverMode mode)19 WebSocketDeflater::WebSocketDeflater(ContextTakeOverMode mode) : mode_(mode) {}
20
~WebSocketDeflater()21 WebSocketDeflater::~WebSocketDeflater() {
22 if (stream_) {
23 deflateEnd(stream_.get());
24 stream_.reset(nullptr);
25 }
26 }
27
Initialize(int window_bits)28 bool WebSocketDeflater::Initialize(int window_bits) {
29 DCHECK(!stream_);
30 stream_ = std::make_unique<z_stream>();
31
32 DCHECK_LE(8, window_bits);
33 DCHECK_GE(15, window_bits);
34
35 // Use a negative value to compress a raw deflate stream.
36 //
37 // Upgrade window_bits = 8 to 9 because zlib is unable to compress at
38 // window_bits = 8. Historically, zlib has silently increased the window size
39 // during compression in this case, although this is no longer done for raw
40 // deflate streams since zlib 1.2.9.
41 //
42 // Because of a zlib deflate quirk, back-references will not use the entire
43 // range of 1 << window_bits, but will instead use a restricted range of (1 <<
44 // window_bits) - 262. With an increased window_bits = 9, back-references will
45 // be within a range of 250. These can still be decompressed with window_bits
46 // = 8 and the 256-byte window used there.
47 //
48 // Both the requirement to do this upgrade and the ability to compress with
49 // window_bits = 9 while expecting a decompressor to function with window_bits
50 // = 8 are quite specific to zlib's particular deflate implementation, but not
51 // specific to any particular inflate implementation.
52 //
53 // See https://crbug.com/691074
54 window_bits = -std::max(window_bits, 9);
55
56 memset(stream_.get(), 0, sizeof(*stream_));
57 int result = deflateInit2(stream_.get(),
58 Z_DEFAULT_COMPRESSION,
59 Z_DEFLATED,
60 window_bits,
61 8, // default mem level
62 Z_DEFAULT_STRATEGY);
63 if (result != Z_OK) {
64 deflateEnd(stream_.get());
65 stream_.reset();
66 return false;
67 }
68 const size_t kFixedBufferSize = 4096;
69 fixed_buffer_.resize(kFixedBufferSize);
70 return true;
71 }
72
AddBytes(const char * data,size_t size)73 bool WebSocketDeflater::AddBytes(const char* data, size_t size) {
74 if (!size)
75 return true;
76
77 are_bytes_added_ = true;
78 stream_->next_in = reinterpret_cast<Bytef*>(const_cast<char*>(data));
79 stream_->avail_in = size;
80
81 int result = Deflate(Z_NO_FLUSH);
82 DCHECK(result != Z_BUF_ERROR || !stream_->avail_in);
83 return result == Z_BUF_ERROR;
84 }
85
Finish()86 bool WebSocketDeflater::Finish() {
87 if (!are_bytes_added_) {
88 // Since consecutive calls of deflate with Z_SYNC_FLUSH and no input
89 // lead to an error, we create and return the output for the empty input
90 // manually.
91 buffer_.push_back('\x00');
92 ResetContext();
93 return true;
94 }
95 stream_->next_in = nullptr;
96 stream_->avail_in = 0;
97
98 int result = Deflate(Z_SYNC_FLUSH);
99 // Deflate returning Z_BUF_ERROR means that it's successfully flushed and
100 // blocked for input data.
101 if (result != Z_BUF_ERROR) {
102 ResetContext();
103 return false;
104 }
105 // Remove 4 octets from the tail as the specification requires.
106 if (CurrentOutputSize() < 4) {
107 ResetContext();
108 return false;
109 }
110 buffer_.resize(buffer_.size() - 4);
111 ResetContext();
112 return true;
113 }
114
PushSyncMark()115 void WebSocketDeflater::PushSyncMark() {
116 DCHECK(!are_bytes_added_);
117 const char data[] = {'\x00', '\x00', '\xff', '\xff'};
118 buffer_.insert(buffer_.end(), &data[0], &data[sizeof(data)]);
119 }
120
GetOutput(size_t size)121 scoped_refptr<IOBufferWithSize> WebSocketDeflater::GetOutput(size_t size) {
122 size_t length_to_copy = std::min(size, buffer_.size());
123 base::circular_deque<char>::iterator begin = buffer_.begin();
124 base::circular_deque<char>::iterator end = begin + length_to_copy;
125
126 auto result = base::MakeRefCounted<IOBufferWithSize>(length_to_copy);
127 std::copy(begin, end, result->data());
128 buffer_.erase(begin, end);
129 return result;
130 }
131
ResetContext()132 void WebSocketDeflater::ResetContext() {
133 if (mode_ == DO_NOT_TAKE_OVER_CONTEXT)
134 deflateReset(stream_.get());
135 are_bytes_added_ = false;
136 }
137
Deflate(int flush)138 int WebSocketDeflater::Deflate(int flush) {
139 int result = Z_OK;
140 do {
141 stream_->next_out = reinterpret_cast<Bytef*>(fixed_buffer_.data());
142 stream_->avail_out = fixed_buffer_.size();
143 result = deflate(stream_.get(), flush);
144 size_t size = fixed_buffer_.size() - stream_->avail_out;
145 buffer_.insert(buffer_.end(), fixed_buffer_.data(),
146 fixed_buffer_.data() + size);
147 } while (result == Z_OK);
148 return result;
149 }
150
151 } // namespace net
152