Revert 205649 "Adding wittman who can submit this change. Either..."
[chromium-blink-merge.git] / net / base / filter.cc
blobe4dbefdd0970d7396a42c9654c2fd97fcd495c1d
1 // Copyright (c) 2011 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 #include "net/base/filter.h"
7 #include "base/files/file_path.h"
8 #include "base/strings/string_util.h"
9 #include "net/base/gzip_filter.h"
10 #include "net/base/io_buffer.h"
11 #include "net/base/mime_util.h"
12 #include "net/base/sdch_filter.h"
14 namespace {
16 // Filter types (using canonical lower case only):
17 const char kDeflate[] = "deflate";
18 const char kGZip[] = "gzip";
19 const char kXGZip[] = "x-gzip";
20 const char kSdch[] = "sdch";
21 // compress and x-compress are currently not supported. If we decide to support
22 // them, we'll need the same mime type compatibility hack we have for gzip. For
23 // more information, see Firefox's nsHttpChannel::ProcessNormal.
24 const char kCompress[] = "compress";
25 const char kXCompress[] = "x-compress";
26 const char kIdentity[] = "identity";
27 const char kUncompressed[] = "uncompressed";
29 // Mime types:
30 const char kApplicationXGzip[] = "application/x-gzip";
31 const char kApplicationGzip[] = "application/gzip";
32 const char kApplicationXGunzip[] = "application/x-gunzip";
33 const char kApplicationXCompress[] = "application/x-compress";
34 const char kApplicationCompress[] = "application/compress";
35 const char kTextHtml[] = "text/html";
37 // Buffer size allocated when de-compressing data.
38 const int kFilterBufSize = 32 * 1024;
40 } // namespace
42 namespace net {
44 FilterContext::~FilterContext() {
47 Filter::~Filter() {}
49 // static
50 Filter* Filter::Factory(const std::vector<FilterType>& filter_types,
51 const FilterContext& filter_context) {
52 if (filter_types.empty())
53 return NULL;
55 Filter* filter_list = NULL; // Linked list of filters.
56 for (size_t i = 0; i < filter_types.size(); i++) {
57 filter_list = PrependNewFilter(filter_types[i], filter_context,
58 kFilterBufSize, filter_list);
59 if (!filter_list)
60 return NULL;
62 return filter_list;
65 // static
66 Filter* Filter::GZipFactory() {
67 return InitGZipFilter(FILTER_TYPE_GZIP, kFilterBufSize);
70 // static
71 Filter* Filter::FactoryForTests(const std::vector<FilterType>& filter_types,
72 const FilterContext& filter_context,
73 int buffer_size) {
74 if (filter_types.empty())
75 return NULL;
77 Filter* filter_list = NULL; // Linked list of filters.
78 for (size_t i = 0; i < filter_types.size(); i++) {
79 filter_list = PrependNewFilter(filter_types[i], filter_context,
80 buffer_size, filter_list);
81 if (!filter_list)
82 return NULL;
84 return filter_list;
87 Filter::FilterStatus Filter::ReadData(char* dest_buffer, int* dest_len) {
88 const int dest_buffer_capacity = *dest_len;
89 if (last_status_ == FILTER_ERROR)
90 return last_status_;
91 if (!next_filter_.get())
92 return last_status_ = ReadFilteredData(dest_buffer, dest_len);
93 if (last_status_ == FILTER_NEED_MORE_DATA && !stream_data_len())
94 return next_filter_->ReadData(dest_buffer, dest_len);
96 do {
97 if (next_filter_->last_status() == FILTER_NEED_MORE_DATA) {
98 PushDataIntoNextFilter();
99 if (FILTER_ERROR == last_status_)
100 return FILTER_ERROR;
102 *dest_len = dest_buffer_capacity; // Reset the input/output parameter.
103 next_filter_->ReadData(dest_buffer, dest_len);
104 if (FILTER_NEED_MORE_DATA == last_status_)
105 return next_filter_->last_status();
107 // In the case where this filter has data internally, and is indicating such
108 // with a last_status_ of FILTER_OK, but at the same time the next filter in
109 // the chain indicated it FILTER_NEED_MORE_DATA, we have to be cautious
110 // about confusing the caller. The API confusion can appear if we return
111 // FILTER_OK (suggesting we have more data in aggregate), but yet we don't
112 // populate our output buffer. When that is the case, we need to
113 // alternately call our filter element, and the next_filter element until we
114 // get out of this state (by pumping data into the next filter until it
115 // outputs data, or it runs out of data and reports that it NEED_MORE_DATA.)
116 } while (FILTER_OK == last_status_ &&
117 FILTER_NEED_MORE_DATA == next_filter_->last_status() &&
118 0 == *dest_len);
120 if (next_filter_->last_status() == FILTER_ERROR)
121 return FILTER_ERROR;
122 return FILTER_OK;
125 bool Filter::FlushStreamBuffer(int stream_data_len) {
126 DCHECK_LE(stream_data_len, stream_buffer_size_);
127 if (stream_data_len <= 0 || stream_data_len > stream_buffer_size_)
128 return false;
130 DCHECK(stream_buffer());
131 // Bail out if there is more data in the stream buffer to be filtered.
132 if (!stream_buffer() || stream_data_len_)
133 return false;
135 next_stream_data_ = stream_buffer()->data();
136 stream_data_len_ = stream_data_len;
137 return true;
140 // static
141 Filter::FilterType Filter::ConvertEncodingToType(
142 const std::string& filter_type) {
143 FilterType type_id;
144 if (LowerCaseEqualsASCII(filter_type, kDeflate)) {
145 type_id = FILTER_TYPE_DEFLATE;
146 } else if (LowerCaseEqualsASCII(filter_type, kGZip) ||
147 LowerCaseEqualsASCII(filter_type, kXGZip)) {
148 type_id = FILTER_TYPE_GZIP;
149 } else if (LowerCaseEqualsASCII(filter_type, kSdch)) {
150 type_id = FILTER_TYPE_SDCH;
151 } else {
152 // Note we also consider "identity" and "uncompressed" UNSUPPORTED as
153 // filter should be disabled in such cases.
154 type_id = FILTER_TYPE_UNSUPPORTED;
156 return type_id;
159 // static
160 void Filter::FixupEncodingTypes(
161 const FilterContext& filter_context,
162 std::vector<FilterType>* encoding_types) {
163 std::string mime_type;
164 bool success = filter_context.GetMimeType(&mime_type);
165 DCHECK(success || mime_type.empty());
167 if ((1 == encoding_types->size()) &&
168 (FILTER_TYPE_GZIP == encoding_types->front())) {
169 if (LowerCaseEqualsASCII(mime_type, kApplicationXGzip) ||
170 LowerCaseEqualsASCII(mime_type, kApplicationGzip) ||
171 LowerCaseEqualsASCII(mime_type, kApplicationXGunzip))
172 // The server has told us that it sent us gziped content with a gzip
173 // content encoding. Sadly, Apache mistakenly sets these headers for all
174 // .gz files. We match Firefox's nsHttpChannel::ProcessNormal and ignore
175 // the Content-Encoding here.
176 encoding_types->clear();
178 GURL url;
179 success = filter_context.GetURL(&url);
180 DCHECK(success);
181 base::FilePath filename =
182 base::FilePath().AppendASCII(url.ExtractFileName());
183 base::FilePath::StringType extension = filename.Extension();
185 if (filter_context.IsDownload()) {
186 // We don't want to decompress gzipped files when the user explicitly
187 // asks to download them.
188 // For the case of svgz files, we use the extension to distinguish
189 // between svgz files and svg files compressed with gzip by the server.
190 // When viewing a .svgz file, we need to uncompress it, but we don't
191 // want to do that when downloading.
192 // See Firefox's nonDecodableExtensions in nsExternalHelperAppService.cpp
193 if (EndsWith(extension, FILE_PATH_LITERAL(".gz"), false) ||
194 LowerCaseEqualsASCII(extension, ".tgz") ||
195 LowerCaseEqualsASCII(extension, ".svgz"))
196 encoding_types->clear();
197 } else {
198 // When the user does not explicitly ask to download a file, if we get a
199 // supported mime type, then we attempt to decompress in order to view it.
200 // However, if it's not a supported mime type, then we will attempt to
201 // download it, and in that case, don't decompress .gz/.tgz files.
202 if ((EndsWith(extension, FILE_PATH_LITERAL(".gz"), false) ||
203 LowerCaseEqualsASCII(extension, ".tgz")) &&
204 !IsSupportedMimeType(mime_type))
205 encoding_types->clear();
209 // If the request was for SDCH content, then we might need additional fixups.
210 if (!filter_context.IsSdchResponse()) {
211 // It was not an SDCH request, so we'll just record stats.
212 if (1 < encoding_types->size()) {
213 // Multiple filters were intended to only be used for SDCH (thus far!)
214 SdchManager::SdchErrorRecovery(
215 SdchManager::MULTIENCODING_FOR_NON_SDCH_REQUEST);
217 if ((1 == encoding_types->size()) &&
218 (FILTER_TYPE_SDCH == encoding_types->front())) {
219 SdchManager::SdchErrorRecovery(
220 SdchManager::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 SdchManager::SdchErrorRecovery(
241 SdchManager::OPTIONAL_GUNZIP_ENCODING_ADDED);
243 return;
246 // There are now several cases to handle for an SDCH request. Foremost, if
247 // the outbound request was stripped so as not to advertise support for
248 // encodings, we might get back content with no encoding, or (for example)
249 // just gzip. We have to be sure that any changes we make allow for such
250 // minimal coding to work. That issue is why we use TENTATIVE filters if we
251 // add any, as those filters sniff the content, and act as pass-through
252 // filters if headers are not found.
254 // If the outbound GET is not modified, then the server will generally try to
255 // send us SDCH encoded content. As that content returns, there are several
256 // corruptions of the header "content-encoding" that proxies may perform (and
257 // have been detected in the wild). We already dealt with the a honest
258 // content encoding of "sdch,gzip" being corrupted into "sdch" with on change
259 // of the actual content. Another common corruption is to either disscard
260 // the accurate content encoding, or to replace it with gzip only (again, with
261 // no change in actual content). The last observed corruption it to actually
262 // change the content, such as by re-gzipping it, and that may happen along
263 // with corruption of the stated content encoding (wow!).
265 // The one unresolved failure mode comes when we advertise a dictionary, and
266 // the server tries to *send* a gzipped file (not gzip encode content), and
267 // then we could do a gzip decode :-(. Since SDCH is only (currently)
268 // supported server side on paths that only send HTML content, this mode has
269 // never surfaced in the wild (and is unlikely to).
270 // We will gather a lot of stats as we perform the fixups
271 if (StartsWithASCII(mime_type, kTextHtml, false)) {
272 // Suspicious case: Advertised dictionary, but server didn't use sdch, and
273 // we're HTML tagged.
274 if (encoding_types->empty()) {
275 SdchManager::SdchErrorRecovery(
276 SdchManager::ADDED_CONTENT_ENCODING);
277 } else if (1 == encoding_types->size()) {
278 SdchManager::SdchErrorRecovery(
279 SdchManager::FIXED_CONTENT_ENCODING);
280 } else {
281 SdchManager::SdchErrorRecovery(
282 SdchManager::FIXED_CONTENT_ENCODINGS);
284 } else {
285 // Remarkable case!?! We advertised an SDCH dictionary, content-encoding
286 // was not marked for SDCH processing: Why did the server suggest an SDCH
287 // dictionary in the first place??. Also, the content isn't
288 // tagged as HTML, despite the fact that SDCH encoding is mostly likely for
289 // HTML: Did some anti-virus system strip this tag (sometimes they strip
290 // accept-encoding headers on the request)?? Does the content encoding not
291 // start with "text/html" for some other reason?? We'll report this as a
292 // fixup to a binary file, but it probably really is text/html (some how).
293 if (encoding_types->empty()) {
294 SdchManager::SdchErrorRecovery(
295 SdchManager::BINARY_ADDED_CONTENT_ENCODING);
296 } else if (1 == encoding_types->size()) {
297 SdchManager::SdchErrorRecovery(
298 SdchManager::BINARY_FIXED_CONTENT_ENCODING);
299 } else {
300 SdchManager::SdchErrorRecovery(
301 SdchManager::BINARY_FIXED_CONTENT_ENCODINGS);
305 // Leave the existing encoding type to be processed first, and add our
306 // tentative decodings to be done afterwards. Vodaphone UK reportedyl will
307 // perform a second layer of gzip encoding atop the server's sdch,gzip
308 // encoding, and then claim that the content encoding is a mere gzip. As a
309 // result we'll need (in that case) to do the gunzip, plus our tentative
310 // gunzip and tentative SDCH decoding.
311 // This approach nicely handles the empty() list as well, and should work with
312 // other (as yet undiscovered) proxies the choose to re-compressed with some
313 // other encoding (such as bzip2, etc.).
314 encoding_types->insert(encoding_types->begin(),
315 FILTER_TYPE_GZIP_HELPING_SDCH);
316 encoding_types->insert(encoding_types->begin(), FILTER_TYPE_SDCH_POSSIBLE);
317 return;
320 Filter::Filter()
321 : stream_buffer_(NULL),
322 stream_buffer_size_(0),
323 next_stream_data_(NULL),
324 stream_data_len_(0),
325 next_filter_(NULL),
326 last_status_(FILTER_NEED_MORE_DATA) {
329 Filter::FilterStatus Filter::CopyOut(char* dest_buffer, int* dest_len) {
330 int out_len;
331 int input_len = *dest_len;
332 *dest_len = 0;
334 if (0 == stream_data_len_)
335 return Filter::FILTER_NEED_MORE_DATA;
337 out_len = std::min(input_len, stream_data_len_);
338 memcpy(dest_buffer, next_stream_data_, out_len);
339 *dest_len += out_len;
340 stream_data_len_ -= out_len;
341 if (0 == stream_data_len_) {
342 next_stream_data_ = NULL;
343 return Filter::FILTER_NEED_MORE_DATA;
344 } else {
345 next_stream_data_ += out_len;
346 return Filter::FILTER_OK;
350 // static
351 Filter* Filter::InitGZipFilter(FilterType type_id, int buffer_size) {
352 scoped_ptr<GZipFilter> gz_filter(new GZipFilter());
353 gz_filter->InitBuffer(buffer_size);
354 return gz_filter->InitDecoding(type_id) ? gz_filter.release() : NULL;
357 // static
358 Filter* Filter::InitSdchFilter(FilterType type_id,
359 const FilterContext& filter_context,
360 int buffer_size) {
361 scoped_ptr<SdchFilter> sdch_filter(new SdchFilter(filter_context));
362 sdch_filter->InitBuffer(buffer_size);
363 return sdch_filter->InitDecoding(type_id) ? sdch_filter.release() : NULL;
366 // static
367 Filter* Filter::PrependNewFilter(FilterType type_id,
368 const FilterContext& filter_context,
369 int buffer_size,
370 Filter* filter_list) {
371 scoped_ptr<Filter> first_filter; // Soon to be start of chain.
372 switch (type_id) {
373 case FILTER_TYPE_GZIP_HELPING_SDCH:
374 case FILTER_TYPE_DEFLATE:
375 case FILTER_TYPE_GZIP:
376 first_filter.reset(InitGZipFilter(type_id, buffer_size));
377 break;
378 case FILTER_TYPE_SDCH:
379 case FILTER_TYPE_SDCH_POSSIBLE:
380 first_filter.reset(InitSdchFilter(type_id, filter_context, buffer_size));
381 break;
382 default:
383 break;
386 if (!first_filter.get())
387 return NULL;
389 first_filter->next_filter_.reset(filter_list);
390 return first_filter.release();
393 void Filter::InitBuffer(int buffer_size) {
394 DCHECK(!stream_buffer());
395 DCHECK_GT(buffer_size, 0);
396 stream_buffer_ = new IOBuffer(buffer_size);
397 stream_buffer_size_ = buffer_size;
400 void Filter::PushDataIntoNextFilter() {
401 IOBuffer* next_buffer = next_filter_->stream_buffer();
402 int next_size = next_filter_->stream_buffer_size();
403 last_status_ = ReadFilteredData(next_buffer->data(), &next_size);
404 if (FILTER_ERROR != last_status_)
405 next_filter_->FlushStreamBuffer(next_size);
408 } // namespace net