xref: /aosp_15_r20/external/cronet/net/websockets/websocket_inflater.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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_inflater.h"
6 
7 #include <string.h>
8 
9 #include <algorithm>
10 #include <vector>
11 
12 #include "base/check.h"
13 #include "base/check_op.h"
14 #include "net/base/io_buffer.h"
15 #include "third_party/zlib/zlib.h"
16 
17 namespace net {
18 
19 namespace {
20 
21 class ShrinkableIOBufferWithSize : public IOBufferWithSize {
22  public:
ShrinkableIOBufferWithSize(size_t size)23   explicit ShrinkableIOBufferWithSize(size_t size) : IOBufferWithSize(size) {}
24 
Shrink(int new_size)25   void Shrink(int new_size) {
26     CHECK_GE(new_size, 0);
27     CHECK_LE(new_size, size_);
28     size_ = new_size;
29   }
30 
31  private:
32   ~ShrinkableIOBufferWithSize() override = default;
33 };
34 
35 }  // namespace
36 
WebSocketInflater()37 WebSocketInflater::WebSocketInflater()
38     : input_queue_(kDefaultInputIOBufferCapacity),
39       output_buffer_(kDefaultBufferCapacity) {}
40 
WebSocketInflater(size_t input_queue_capacity,size_t output_buffer_capacity)41 WebSocketInflater::WebSocketInflater(size_t input_queue_capacity,
42                                      size_t output_buffer_capacity)
43     : input_queue_(input_queue_capacity),
44       output_buffer_(output_buffer_capacity) {
45   DCHECK_GT(input_queue_capacity, 0u);
46   DCHECK_GT(output_buffer_capacity, 0u);
47 }
48 
Initialize(int window_bits)49 bool WebSocketInflater::Initialize(int window_bits) {
50   DCHECK_LE(8, window_bits);
51   DCHECK_GE(15, window_bits);
52   stream_ = std::make_unique<z_stream>();
53   memset(stream_.get(), 0, sizeof(*stream_));
54   int result = inflateInit2(stream_.get(), -window_bits);
55   if (result != Z_OK) {
56     inflateEnd(stream_.get());
57     stream_.reset();
58     return false;
59   }
60   return true;
61 }
62 
~WebSocketInflater()63 WebSocketInflater::~WebSocketInflater() {
64   if (stream_) {
65     inflateEnd(stream_.get());
66     stream_.reset();
67   }
68 }
69 
AddBytes(const char * data,size_t size)70 bool WebSocketInflater::AddBytes(const char* data, size_t size) {
71   if (!size)
72     return true;
73 
74   if (!input_queue_.IsEmpty()) {
75     // choked
76     input_queue_.Push(data, size);
77     return true;
78   }
79 
80   int result = InflateWithFlush(data, size);
81   if (stream_->avail_in > 0)
82     input_queue_.Push(&data[size - stream_->avail_in], stream_->avail_in);
83 
84   return result == Z_OK || result == Z_BUF_ERROR;
85 }
86 
Finish()87 bool WebSocketInflater::Finish() {
88   return AddBytes("\x00\x00\xff\xff", 4);
89 }
90 
GetOutput(size_t size)91 scoped_refptr<IOBufferWithSize> WebSocketInflater::GetOutput(size_t size) {
92   auto buffer = base::MakeRefCounted<ShrinkableIOBufferWithSize>(size);
93   size_t num_bytes_copied = 0;
94 
95   while (num_bytes_copied < size && output_buffer_.Size() > 0) {
96     size_t num_bytes_to_copy =
97         std::min(output_buffer_.Size(), size - num_bytes_copied);
98     output_buffer_.Read(&buffer->data()[num_bytes_copied], num_bytes_to_copy);
99     num_bytes_copied += num_bytes_to_copy;
100     int result = InflateChokedInput();
101     if (result != Z_OK && result != Z_BUF_ERROR)
102       return nullptr;
103   }
104   buffer->Shrink(num_bytes_copied);
105   return buffer;
106 }
107 
InflateWithFlush(const char * next_in,size_t avail_in)108 int WebSocketInflater::InflateWithFlush(const char* next_in, size_t avail_in) {
109   int result = Inflate(next_in, avail_in, Z_NO_FLUSH);
110   if (result != Z_OK && result != Z_BUF_ERROR)
111     return result;
112 
113   if (CurrentOutputSize() > 0)
114     return result;
115   // CurrentOutputSize() == 0 means there is no data to be output,
116   // so we should make sure it by using Z_SYNC_FLUSH.
117   return Inflate(reinterpret_cast<const char*>(stream_->next_in),
118                  stream_->avail_in,
119                  Z_SYNC_FLUSH);
120 }
121 
Inflate(const char * next_in,size_t avail_in,int flush)122 int WebSocketInflater::Inflate(const char* next_in,
123                                size_t avail_in,
124                                int flush) {
125   stream_->next_in = reinterpret_cast<Bytef*>(const_cast<char*>(next_in));
126   stream_->avail_in = avail_in;
127 
128   int result = Z_BUF_ERROR;
129   do {
130     std::pair<char*, size_t> tail = output_buffer_.GetTail();
131     if (!tail.second)
132       break;
133 
134     stream_->next_out = reinterpret_cast<Bytef*>(tail.first);
135     stream_->avail_out = tail.second;
136     result = inflate(stream_.get(), flush);
137     output_buffer_.AdvanceTail(tail.second - stream_->avail_out);
138     if (result == Z_STREAM_END) {
139       // Received a block with BFINAL set to 1. Reset the decompression state.
140       result = inflateReset(stream_.get());
141     } else if (tail.second == stream_->avail_out) {
142       break;
143     }
144   } while (result == Z_OK || result == Z_BUF_ERROR);
145   return result;
146 }
147 
InflateChokedInput()148 int WebSocketInflater::InflateChokedInput() {
149   if (input_queue_.IsEmpty())
150     return InflateWithFlush(nullptr, 0);
151 
152   int result = Z_BUF_ERROR;
153   while (!input_queue_.IsEmpty()) {
154     std::pair<char*, size_t> top = input_queue_.Top();
155 
156     result = InflateWithFlush(top.first, top.second);
157     input_queue_.Consume(top.second - stream_->avail_in);
158 
159     if (result != Z_OK && result != Z_BUF_ERROR)
160       return result;
161 
162     if (stream_->avail_in > 0) {
163       // There are some data which are not consumed.
164       break;
165     }
166   }
167   return result;
168 }
169 
OutputBuffer(size_t capacity)170 WebSocketInflater::OutputBuffer::OutputBuffer(size_t capacity)
171     : capacity_(capacity),
172       buffer_(capacity_ + 1)  // 1 for sentinel
173 {}
174 
175 WebSocketInflater::OutputBuffer::~OutputBuffer() = default;
176 
Size() const177 size_t WebSocketInflater::OutputBuffer::Size() const {
178   return (tail_ + buffer_.size() - head_) % buffer_.size();
179 }
180 
GetTail()181 std::pair<char*, size_t> WebSocketInflater::OutputBuffer::GetTail() {
182   DCHECK_LT(tail_, buffer_.size());
183   return std::pair(&buffer_[tail_],
184                    std::min(capacity_ - Size(), buffer_.size() - tail_));
185 }
186 
Read(char * dest,size_t size)187 void WebSocketInflater::OutputBuffer::Read(char* dest, size_t size) {
188   DCHECK_LE(size, Size());
189 
190   size_t num_bytes_copied = 0;
191   if (tail_ < head_) {
192     size_t num_bytes_to_copy = std::min(size, buffer_.size() - head_);
193     DCHECK_LT(head_, buffer_.size());
194     memcpy(&dest[num_bytes_copied], &buffer_[head_], num_bytes_to_copy);
195     AdvanceHead(num_bytes_to_copy);
196     num_bytes_copied += num_bytes_to_copy;
197   }
198 
199   if (num_bytes_copied == size)
200     return;
201   DCHECK_LE(head_, tail_);
202   size_t num_bytes_to_copy = size - num_bytes_copied;
203   DCHECK_LE(num_bytes_to_copy, tail_ - head_);
204   DCHECK_LT(head_, buffer_.size());
205   memcpy(&dest[num_bytes_copied], &buffer_[head_], num_bytes_to_copy);
206   AdvanceHead(num_bytes_to_copy);
207   num_bytes_copied += num_bytes_to_copy;
208   DCHECK_EQ(size, num_bytes_copied);
209   return;
210 }
211 
AdvanceHead(size_t advance)212 void WebSocketInflater::OutputBuffer::AdvanceHead(size_t advance) {
213   DCHECK_LE(advance, Size());
214   head_ = (head_ + advance) % buffer_.size();
215 }
216 
AdvanceTail(size_t advance)217 void WebSocketInflater::OutputBuffer::AdvanceTail(size_t advance) {
218   DCHECK_LE(advance + Size(), capacity_);
219   tail_ = (tail_ + advance) % buffer_.size();
220 }
221 
InputQueue(size_t capacity)222 WebSocketInflater::InputQueue::InputQueue(size_t capacity)
223     : capacity_(capacity) {}
224 
225 WebSocketInflater::InputQueue::~InputQueue() = default;
226 
Top()227 std::pair<char*, size_t> WebSocketInflater::InputQueue::Top() {
228   DCHECK(!IsEmpty());
229   if (buffers_.size() == 1) {
230     return std::pair(&buffers_.front()->data()[head_of_first_buffer_],
231                      tail_of_last_buffer_ - head_of_first_buffer_);
232   }
233   return std::pair(&buffers_.front()->data()[head_of_first_buffer_],
234                    capacity_ - head_of_first_buffer_);
235 }
236 
Push(const char * data,size_t size)237 void WebSocketInflater::InputQueue::Push(const char* data, size_t size) {
238   if (!size)
239     return;
240 
241   size_t num_copied_bytes = 0;
242   if (!IsEmpty())
243     num_copied_bytes += PushToLastBuffer(data, size);
244 
245   while (num_copied_bytes < size) {
246     DCHECK(IsEmpty() || tail_of_last_buffer_ == capacity_);
247 
248     buffers_.push_back(base::MakeRefCounted<IOBufferWithSize>(capacity_));
249     tail_of_last_buffer_ = 0;
250     num_copied_bytes +=
251         PushToLastBuffer(&data[num_copied_bytes], size - num_copied_bytes);
252   }
253 }
254 
Consume(size_t size)255 void WebSocketInflater::InputQueue::Consume(size_t size) {
256   DCHECK(!IsEmpty());
257   DCHECK_LE(size + head_of_first_buffer_, capacity_);
258 
259   head_of_first_buffer_ += size;
260   if (head_of_first_buffer_ == capacity_) {
261     buffers_.pop_front();
262     head_of_first_buffer_ = 0;
263   }
264   if (buffers_.size() == 1 && head_of_first_buffer_ == tail_of_last_buffer_) {
265     buffers_.pop_front();
266     head_of_first_buffer_ = 0;
267     tail_of_last_buffer_ = 0;
268   }
269 }
270 
PushToLastBuffer(const char * data,size_t size)271 size_t WebSocketInflater::InputQueue::PushToLastBuffer(const char* data,
272                                                        size_t size) {
273   DCHECK(!IsEmpty());
274   size_t num_bytes_to_copy = std::min(size, capacity_ - tail_of_last_buffer_);
275   if (!num_bytes_to_copy)
276     return 0;
277   IOBufferWithSize* buffer = buffers_.back().get();
278   memcpy(&buffer->data()[tail_of_last_buffer_], data, num_bytes_to_copy);
279   tail_of_last_buffer_ += num_bytes_to_copy;
280   return num_bytes_to_copy;
281 }
282 
283 }  // namespace net
284