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