Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / filter / filter.cc
blob708ad814eea99537beb746e9d4f120d23581f026
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // The basic usage of the Filter interface is described in the comment at
6 // the beginning of filter.h. If Filter::Factory is passed a vector of
7 // size greater than 1, that interface is implemented by a series of filters
8 // connected in a chain. In such a case the first filter
9 // in the chain proxies calls to ReadData() so that its return values
10 // apply to the entire chain.
12 // In a filter chain, the data flows from first filter (held by the
13 // caller) down the chain. When ReadData() is called on any filter
14 // except for the last filter, it proxies the call down the chain,
15 // filling in the input buffers of subsequent filters if needed (==
16 // that filter's last_status() value is FILTER_NEED_MORE_DATA) and
17 // available (== the current filter has data it can output). The last
18 // Filter will then output data if possible, and return
19 // FILTER_NEED_MORE_DATA if not. Because the indirection pushes
20 // data along the filter chain at each level if it's available and the
21 // next filter needs it, a return value of FILTER_NEED_MORE_DATA from the
22 // final filter will apply to the entire chain.
24 #include "net/filter/filter.h"
26 #include "base/files/file_path.h"
27 #include "base/strings/string_util.h"
28 #include "base/values.h"
29 #include "net/base/io_buffer.h"
30 #include "net/base/sdch_net_log_params.h"
31 #include "net/filter/gzip_filter.h"
32 #include "net/filter/sdch_filter.h"
33 #include "net/url_request/url_request_context.h"
34 #include "url/gurl.h"
36 namespace net {
38 namespace {
40 // Filter types (using canonical lower case only):
41 const char kDeflate[] = "deflate";
42 const char kGZip[] = "gzip";
43 const char kXGZip[] = "x-gzip";
44 const char kSdch[] = "sdch";
45 // compress and x-compress are currently not supported. If we decide to support
46 // them, we'll need the same mime type compatibility hack we have for gzip. For
47 // more information, see Firefox's nsHttpChannel::ProcessNormal.
49 // Mime types:
50 const char kTextHtml[] = "text/html";
52 // Buffer size allocated when de-compressing data.
53 const int kFilterBufSize = 32 * 1024;
55 void LogSdchProblem(const FilterContext& filter_context,
56 SdchProblemCode problem) {
57 SdchManager::SdchErrorRecovery(problem);
58 filter_context.GetNetLog().AddEvent(
59 NetLog::TYPE_SDCH_DECODING_ERROR,
60 base::Bind(&NetLogSdchResourceProblemCallback, problem));
63 std::string FilterTypeAsString(Filter::FilterType type_id) {
64 switch (type_id) {
65 case Filter::FILTER_TYPE_DEFLATE:
66 return "FILTER_TYPE_DEFLATE";
67 case Filter::FILTER_TYPE_GZIP:
68 return "FILTER_TYPE_GZIP";
69 case Filter::FILTER_TYPE_GZIP_HELPING_SDCH:
70 return "FILTER_TYPE_GZIP_HELPING_SDCH";
71 case Filter::FILTER_TYPE_SDCH:
72 return "FILTER_TYPE_SDCH";
73 case Filter::FILTER_TYPE_SDCH_POSSIBLE :
74 return "FILTER_TYPE_SDCH_POSSIBLE ";
75 case Filter::FILTER_TYPE_UNSUPPORTED:
76 return "FILTER_TYPE_UNSUPPORTED";
78 return "";
81 } // namespace
83 FilterContext::~FilterContext() {
86 Filter::~Filter() {}
88 // static
89 Filter* Filter::Factory(const std::vector<FilterType>& filter_types,
90 const FilterContext& filter_context) {
91 if (filter_types.empty())
92 return NULL;
94 Filter* filter_list = NULL; // Linked list of filters.
95 for (size_t i = 0; i < filter_types.size(); i++) {
96 filter_list = PrependNewFilter(filter_types[i], filter_context,
97 kFilterBufSize, filter_list);
98 if (!filter_list)
99 return NULL;
101 return filter_list;
104 // static
105 Filter* Filter::GZipFactory() {
106 return InitGZipFilter(FILTER_TYPE_GZIP, kFilterBufSize);
109 // static
110 Filter* Filter::FactoryForTests(const std::vector<FilterType>& filter_types,
111 const FilterContext& filter_context,
112 int buffer_size) {
113 if (filter_types.empty())
114 return NULL;
116 Filter* filter_list = NULL; // Linked list of filters.
117 for (size_t i = 0; i < filter_types.size(); i++) {
118 filter_list = PrependNewFilter(filter_types[i], filter_context,
119 buffer_size, filter_list);
120 if (!filter_list)
121 return NULL;
123 return filter_list;
126 Filter::FilterStatus Filter::ReadData(char* dest_buffer, int* dest_len) {
127 const int dest_buffer_capacity = *dest_len;
128 if (last_status_ == FILTER_ERROR)
129 return last_status_;
130 if (!next_filter_.get())
131 return last_status_ = ReadFilteredData(dest_buffer, dest_len);
133 // This filter needs more data, but it's not clear that the rest of
134 // the chain does; delegate the actual status return to the next filter.
135 if (last_status_ == FILTER_NEED_MORE_DATA && !stream_data_len())
136 return next_filter_->ReadData(dest_buffer, dest_len);
138 do {
139 if (next_filter_->last_status() == FILTER_NEED_MORE_DATA) {
140 PushDataIntoNextFilter();
141 if (FILTER_ERROR == last_status_)
142 return FILTER_ERROR;
144 *dest_len = dest_buffer_capacity; // Reset the input/output parameter.
145 next_filter_->ReadData(dest_buffer, dest_len);
146 if (FILTER_NEED_MORE_DATA == last_status_)
147 return next_filter_->last_status();
149 // In the case where this filter has data internally, and is indicating such
150 // with a last_status_ of FILTER_OK, but at the same time the next filter in
151 // the chain indicated it FILTER_NEED_MORE_DATA, we have to be cautious
152 // about confusing the caller. The API confusion can appear if we return
153 // FILTER_OK (suggesting we have more data in aggregate), but yet we don't
154 // populate our output buffer. When that is the case, we need to
155 // alternately call our filter element, and the next_filter element until we
156 // get out of this state (by pumping data into the next filter until it
157 // outputs data, or it runs out of data and reports that it NEED_MORE_DATA.)
158 } while (FILTER_OK == last_status_ &&
159 FILTER_NEED_MORE_DATA == next_filter_->last_status() &&
160 0 == *dest_len);
162 if (next_filter_->last_status() == FILTER_ERROR)
163 return FILTER_ERROR;
164 return FILTER_OK;
167 bool Filter::FlushStreamBuffer(int stream_data_len) {
168 DCHECK_LE(stream_data_len, stream_buffer_size_);
169 if (stream_data_len <= 0 || stream_data_len > stream_buffer_size_)
170 return false;
172 DCHECK(stream_buffer());
173 // Bail out if there is more data in the stream buffer to be filtered.
174 if (!stream_buffer() || stream_data_len_)
175 return false;
177 next_stream_data_ = stream_buffer()->data();
178 stream_data_len_ = stream_data_len;
179 last_status_ = FILTER_OK;
180 return true;
183 // static
184 Filter::FilterType Filter::ConvertEncodingToType(
185 const std::string& filter_type) {
186 FilterType type_id;
187 if (base::LowerCaseEqualsASCII(filter_type, kDeflate)) {
188 type_id = FILTER_TYPE_DEFLATE;
189 } else if (base::LowerCaseEqualsASCII(filter_type, kGZip) ||
190 base::LowerCaseEqualsASCII(filter_type, kXGZip)) {
191 type_id = FILTER_TYPE_GZIP;
192 } else if (base::LowerCaseEqualsASCII(filter_type, kSdch)) {
193 type_id = FILTER_TYPE_SDCH;
194 } else {
195 // Note we also consider "identity" and "uncompressed" UNSUPPORTED as
196 // filter should be disabled in such cases.
197 type_id = FILTER_TYPE_UNSUPPORTED;
199 return type_id;
202 // static
203 void Filter::FixupEncodingTypes(
204 const FilterContext& filter_context,
205 std::vector<FilterType>* encoding_types) {
206 std::string mime_type;
207 bool success = filter_context.GetMimeType(&mime_type);
208 DCHECK(success || mime_type.empty());
210 // If the request was for SDCH content, then we might need additional fixups.
211 if (!filter_context.SdchDictionariesAdvertised()) {
212 // It was not an SDCH request, so we'll just record stats.
213 if (1 < encoding_types->size()) {
214 // Multiple filters were intended to only be used for SDCH (thus far!)
215 LogSdchProblem(filter_context, SDCH_MULTIENCODING_FOR_NON_SDCH_REQUEST);
217 if ((1 == encoding_types->size()) &&
218 (FILTER_TYPE_SDCH == encoding_types->front())) {
219 LogSdchProblem(filter_context,
220 SDCH_SDCH_CONTENT_ENCODE_FOR_NON_SDCH_REQUEST);
222 return;
225 // The request was tagged as an SDCH request, which means the server supplied
226 // a dictionary, and we advertised it in the request. Some proxies will do
227 // very strange things to the request, or the response, so we have to handle
228 // them gracefully.
230 // If content encoding included SDCH, then everything is "relatively" fine.
231 if (!encoding_types->empty() &&
232 (FILTER_TYPE_SDCH == encoding_types->front())) {
233 // Some proxies (found currently in Argentina) strip the Content-Encoding
234 // text from "sdch,gzip" to a mere "sdch" without modifying the compressed
235 // payload. To handle this gracefully, we simulate the "probably" deleted
236 // ",gzip" by appending a tentative gzip decode, which will default to a
237 // no-op pass through filter if it doesn't get gzip headers where expected.
238 if (1 == encoding_types->size()) {
239 encoding_types->push_back(FILTER_TYPE_GZIP_HELPING_SDCH);
240 LogSdchProblem(filter_context, SDCH_OPTIONAL_GUNZIP_ENCODING_ADDED);
242 return;
245 // There are now several cases to handle for an SDCH request. Foremost, if
246 // the outbound request was stripped so as not to advertise support for
247 // encodings, we might get back content with no encoding, or (for example)
248 // just gzip. We have to be sure that any changes we make allow for such
249 // minimal coding to work. That issue is why we use TENTATIVE filters if we
250 // add any, as those filters sniff the content, and act as pass-through
251 // filters if headers are not found.
253 // If the outbound GET is not modified, then the server will generally try to
254 // send us SDCH encoded content. As that content returns, there are several
255 // corruptions of the header "content-encoding" that proxies may perform (and
256 // have been detected in the wild). We already dealt with the a honest
257 // content encoding of "sdch,gzip" being corrupted into "sdch" with on change
258 // of the actual content. Another common corruption is to either disscard
259 // the accurate content encoding, or to replace it with gzip only (again, with
260 // no change in actual content). The last observed corruption it to actually
261 // change the content, such as by re-gzipping it, and that may happen along
262 // with corruption of the stated content encoding (wow!).
264 // The one unresolved failure mode comes when we advertise a dictionary, and
265 // the server tries to *send* a gzipped file (not gzip encode content), and
266 // then we could do a gzip decode :-(. Since SDCH is only (currently)
267 // supported server side on paths that only send HTML content, this mode has
268 // never surfaced in the wild (and is unlikely to).
269 // We will gather a lot of stats as we perform the fixups
270 if (base::StartsWith(mime_type, kTextHtml,
271 base::CompareCase::INSENSITIVE_ASCII)) {
272 // Suspicious case: Advertised dictionary, but server didn't use sdch, and
273 // we're HTML tagged.
274 if (encoding_types->empty()) {
275 LogSdchProblem(filter_context, SDCH_ADDED_CONTENT_ENCODING);
276 } else if (1 == encoding_types->size()) {
277 LogSdchProblem(filter_context, SDCH_FIXED_CONTENT_ENCODING);
278 } else {
279 LogSdchProblem(filter_context, SDCH_FIXED_CONTENT_ENCODINGS);
281 } else {
282 // Remarkable case!?! We advertised an SDCH dictionary, content-encoding
283 // was not marked for SDCH processing: Why did the server suggest an SDCH
284 // dictionary in the first place??. Also, the content isn't
285 // tagged as HTML, despite the fact that SDCH encoding is mostly likely for
286 // HTML: Did some anti-virus system strip this tag (sometimes they strip
287 // accept-encoding headers on the request)?? Does the content encoding not
288 // start with "text/html" for some other reason?? We'll report this as a
289 // fixup to a binary file, but it probably really is text/html (some how).
290 if (encoding_types->empty()) {
291 LogSdchProblem(filter_context, SDCH_BINARY_ADDED_CONTENT_ENCODING);
292 } else if (1 == encoding_types->size()) {
293 LogSdchProblem(filter_context, SDCH_BINARY_FIXED_CONTENT_ENCODING);
294 } else {
295 LogSdchProblem(filter_context, SDCH_BINARY_FIXED_CONTENT_ENCODINGS);
299 // Leave the existing encoding type to be processed first, and add our
300 // tentative decodings to be done afterwards. Vodaphone UK reportedyl will
301 // perform a second layer of gzip encoding atop the server's sdch,gzip
302 // encoding, and then claim that the content encoding is a mere gzip. As a
303 // result we'll need (in that case) to do the gunzip, plus our tentative
304 // gunzip and tentative SDCH decoding.
305 // This approach nicely handles the empty() list as well, and should work with
306 // other (as yet undiscovered) proxies the choose to re-compressed with some
307 // other encoding (such as bzip2, etc.).
308 encoding_types->insert(encoding_types->begin(),
309 FILTER_TYPE_GZIP_HELPING_SDCH);
310 encoding_types->insert(encoding_types->begin(), FILTER_TYPE_SDCH_POSSIBLE);
311 return;
314 std::string Filter::OrderedFilterList() const {
315 if (next_filter_) {
316 return FilterTypeAsString(type_id_) + "," +
317 next_filter_->OrderedFilterList();
318 } else {
319 return FilterTypeAsString(type_id_);
323 Filter::Filter(FilterType type_id)
324 : stream_buffer_(NULL),
325 stream_buffer_size_(0),
326 next_stream_data_(NULL),
327 stream_data_len_(0),
328 last_status_(FILTER_NEED_MORE_DATA),
329 type_id_(type_id) {}
331 Filter::FilterStatus Filter::CopyOut(char* dest_buffer, int* dest_len) {
332 int out_len;
333 int input_len = *dest_len;
334 *dest_len = 0;
336 if (0 == stream_data_len_)
337 return Filter::FILTER_NEED_MORE_DATA;
339 out_len = std::min(input_len, stream_data_len_);
340 memcpy(dest_buffer, next_stream_data_, out_len);
341 *dest_len += out_len;
342 stream_data_len_ -= out_len;
343 if (0 == stream_data_len_) {
344 next_stream_data_ = NULL;
345 return Filter::FILTER_NEED_MORE_DATA;
346 } else {
347 next_stream_data_ += out_len;
348 return Filter::FILTER_OK;
352 // static
353 Filter* Filter::InitGZipFilter(FilterType type_id, int buffer_size) {
354 scoped_ptr<GZipFilter> gz_filter(new GZipFilter(type_id));
355 gz_filter->InitBuffer(buffer_size);
356 return gz_filter->InitDecoding(type_id) ? gz_filter.release() : NULL;
359 // static
360 Filter* Filter::InitSdchFilter(FilterType type_id,
361 const FilterContext& filter_context,
362 int buffer_size) {
363 scoped_ptr<SdchFilter> sdch_filter(new SdchFilter(type_id, filter_context));
364 sdch_filter->InitBuffer(buffer_size);
365 return sdch_filter->InitDecoding(type_id) ? sdch_filter.release() : NULL;
368 // static
369 Filter* Filter::PrependNewFilter(FilterType type_id,
370 const FilterContext& filter_context,
371 int buffer_size,
372 Filter* filter_list) {
373 scoped_ptr<Filter> first_filter; // Soon to be start of chain.
374 switch (type_id) {
375 case FILTER_TYPE_GZIP_HELPING_SDCH:
376 case FILTER_TYPE_DEFLATE:
377 case FILTER_TYPE_GZIP:
378 first_filter.reset(InitGZipFilter(type_id, buffer_size));
379 break;
380 case FILTER_TYPE_SDCH:
381 case FILTER_TYPE_SDCH_POSSIBLE:
382 if (filter_context.GetURLRequestContext()->sdch_manager() &&
383 SdchManager::sdch_enabled()) {
384 first_filter.reset(
385 InitSdchFilter(type_id, filter_context, buffer_size));
387 break;
388 default:
389 break;
392 if (!first_filter.get())
393 return NULL;
395 first_filter->next_filter_.reset(filter_list);
396 return first_filter.release();
399 void Filter::InitBuffer(int buffer_size) {
400 DCHECK(!stream_buffer());
401 DCHECK_GT(buffer_size, 0);
402 stream_buffer_ = new IOBuffer(buffer_size);
403 stream_buffer_size_ = buffer_size;
406 void Filter::PushDataIntoNextFilter() {
407 IOBuffer* next_buffer = next_filter_->stream_buffer();
408 int next_size = next_filter_->stream_buffer_size();
409 last_status_ = ReadFilteredData(next_buffer->data(), &next_size);
410 if (FILTER_ERROR != last_status_)
411 next_filter_->FlushStreamBuffer(next_size);
414 } // namespace net