Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / net / filter / filter.cc
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.
4
5 #include "net/filter/filter.h"
6
7 #include "base/files/file_path.h"
8 #include "base/strings/string_util.h"
9 #include "net/base/io_buffer.h"
10 #include "net/base/mime_util.h"
11 #include "net/filter/gzip_filter.h"
12 #include "net/filter/sdch_filter.h"
13
14 namespace {
15
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
25 // Mime types:
26 const char kApplicationXGzip[]     = "application/x-gzip";
27 const char kApplicationGzip[]      = "application/gzip";
28 const char kApplicationXGunzip[]   = "application/x-gunzip";
29 const char kTextHtml[]             = "text/html";
30
31 // Buffer size allocated when de-compressing data.
32 const int kFilterBufSize = 32 * 1024;
33
34 }  // namespace
35
36 namespace net {
37
38 FilterContext::~FilterContext() {
39 }
40
41 Filter::~Filter() {}
42
43 // static
44 Filter* Filter::Factory(const std::vector<FilterType>& filter_types,
45                         const FilterContext& filter_context) {
46   if (filter_types.empty())
47     return NULL;
48
49   Filter* filter_list = NULL;  // Linked list of filters.
50   for (size_t i = 0; i < filter_types.size(); i++) {
51     filter_list = PrependNewFilter(filter_types[i], filter_context,
52                                    kFilterBufSize, filter_list);
53     if (!filter_list)
54       return NULL;
55   }
56   return filter_list;
57 }
58
59 // static
60 Filter* Filter::GZipFactory() {
61   return InitGZipFilter(FILTER_TYPE_GZIP, kFilterBufSize);
62 }
63
64 // static
65 Filter* Filter::FactoryForTests(const std::vector<FilterType>& filter_types,
66                                 const FilterContext& filter_context,
67                                 int buffer_size) {
68   if (filter_types.empty())
69     return NULL;
70
71   Filter* filter_list = NULL;  // Linked list of filters.
72   for (size_t i = 0; i < filter_types.size(); i++) {
73     filter_list = PrependNewFilter(filter_types[i], filter_context,
74                                    buffer_size, filter_list);
75     if (!filter_list)
76       return NULL;
77   }
78   return filter_list;
79 }
80
81 Filter::FilterStatus Filter::ReadData(char* dest_buffer, int* dest_len) {
82   const int dest_buffer_capacity = *dest_len;
83   if (last_status_ == FILTER_ERROR)
84     return last_status_;
85   if (!next_filter_.get())
86     return last_status_ = ReadFilteredData(dest_buffer, dest_len);
87   if (last_status_ == FILTER_NEED_MORE_DATA && !stream_data_len())
88     return next_filter_->ReadData(dest_buffer, dest_len);
89
90   do {
91     if (next_filter_->last_status() == FILTER_NEED_MORE_DATA) {
92       PushDataIntoNextFilter();
93       if (FILTER_ERROR == last_status_)
94         return FILTER_ERROR;
95     }
96     *dest_len = dest_buffer_capacity;  // Reset the input/output parameter.
97     next_filter_->ReadData(dest_buffer, dest_len);
98     if (FILTER_NEED_MORE_DATA == last_status_)
99         return next_filter_->last_status();
100
101     // In the case where this filter has data internally, and is indicating such
102     // with a last_status_ of FILTER_OK, but at the same time the next filter in
103     // the chain indicated it FILTER_NEED_MORE_DATA, we have to be cautious
104     // about confusing the caller.  The API confusion can appear if we return
105     // FILTER_OK (suggesting we have more data in aggregate), but yet we don't
106     // populate our output buffer.  When that is the case, we need to
107     // alternately call our filter element, and the next_filter element until we
108     // get out of this state (by pumping data into the next filter until it
109     // outputs data, or it runs out of data and reports that it NEED_MORE_DATA.)
110   } while (FILTER_OK == last_status_ &&
111            FILTER_NEED_MORE_DATA == next_filter_->last_status() &&
112            0 == *dest_len);
113
114   if (next_filter_->last_status() == FILTER_ERROR)
115     return FILTER_ERROR;
116   return FILTER_OK;
117 }
118
119 bool Filter::FlushStreamBuffer(int stream_data_len) {
120   DCHECK_LE(stream_data_len, stream_buffer_size_);
121   if (stream_data_len <= 0 || stream_data_len > stream_buffer_size_)
122     return false;
123
124   DCHECK(stream_buffer());
125   // Bail out if there is more data in the stream buffer to be filtered.
126   if (!stream_buffer() || stream_data_len_)
127     return false;
128
129   next_stream_data_ = stream_buffer()->data();
130   stream_data_len_ = stream_data_len;
131   return true;
132 }
133
134 // static
135 Filter::FilterType Filter::ConvertEncodingToType(
136     const std::string& filter_type) {
137   FilterType type_id;
138   if (LowerCaseEqualsASCII(filter_type, kDeflate)) {
139     type_id = FILTER_TYPE_DEFLATE;
140   } else if (LowerCaseEqualsASCII(filter_type, kGZip) ||
141              LowerCaseEqualsASCII(filter_type, kXGZip)) {
142     type_id = FILTER_TYPE_GZIP;
143   } else if (LowerCaseEqualsASCII(filter_type, kSdch)) {
144     type_id = FILTER_TYPE_SDCH;
145   } else {
146     // Note we also consider "identity" and "uncompressed" UNSUPPORTED as
147     // filter should be disabled in such cases.
148     type_id = FILTER_TYPE_UNSUPPORTED;
149   }
150   return type_id;
151 }
152
153 // static
154 void Filter::FixupEncodingTypes(
155     const FilterContext& filter_context,
156     std::vector<FilterType>* encoding_types) {
157   std::string mime_type;
158   bool success = filter_context.GetMimeType(&mime_type);
159   DCHECK(success || mime_type.empty());
160
161   if ((1 == encoding_types->size()) &&
162       (FILTER_TYPE_GZIP == encoding_types->front())) {
163     if (LowerCaseEqualsASCII(mime_type, kApplicationXGzip) ||
164         LowerCaseEqualsASCII(mime_type, kApplicationGzip) ||
165         LowerCaseEqualsASCII(mime_type, kApplicationXGunzip))
166       // The server has told us that it sent us gziped content with a gzip
167       // content encoding.  Sadly, Apache mistakenly sets these headers for all
168       // .gz files.  We match Firefox's nsHttpChannel::ProcessNormal and ignore
169       // the Content-Encoding here.
170       encoding_types->clear();
171
172     GURL url;
173     success = filter_context.GetURL(&url);
174     DCHECK(success);
175     base::FilePath filename =
176         base::FilePath().AppendASCII(url.ExtractFileName());
177     base::FilePath::StringType extension = filename.Extension();
178
179     if (filter_context.IsDownload()) {
180       // We don't want to decompress gzipped files when the user explicitly
181       // asks to download them.
182       // For the case of svgz files, we use the extension to distinguish
183       // between svgz files and svg files compressed with gzip by the server.
184       // When viewing a .svgz file, we need to uncompress it, but we don't
185       // want to do that when downloading.
186       // See Firefox's nonDecodableExtensions in nsExternalHelperAppService.cpp
187       if (EndsWith(extension, FILE_PATH_LITERAL(".gz"), false) ||
188           LowerCaseEqualsASCII(extension, ".tgz") ||
189           LowerCaseEqualsASCII(extension, ".svgz"))
190         encoding_types->clear();
191     } else {
192       // When the user does not explicitly ask to download a file, if we get a
193       // supported mime type, then we attempt to decompress in order to view it.
194       // However, if it's not a supported mime type, then we will attempt to
195       // download it, and in that case, don't decompress .gz/.tgz files.
196       if ((EndsWith(extension, FILE_PATH_LITERAL(".gz"), false) ||
197            LowerCaseEqualsASCII(extension, ".tgz")) &&
198           !IsSupportedMimeType(mime_type))
199         encoding_types->clear();
200     }
201   }
202
203   // If the request was for SDCH content, then we might need additional fixups.
204   if (!filter_context.IsSdchResponse()) {
205     // It was not an SDCH request, so we'll just record stats.
206     if (1 < encoding_types->size()) {
207       // Multiple filters were intended to only be used for SDCH (thus far!)
208       SdchManager::SdchErrorRecovery(
209           SdchManager::MULTIENCODING_FOR_NON_SDCH_REQUEST);
210     }
211     if ((1 == encoding_types->size()) &&
212         (FILTER_TYPE_SDCH == encoding_types->front())) {
213         SdchManager::SdchErrorRecovery(
214             SdchManager::SDCH_CONTENT_ENCODE_FOR_NON_SDCH_REQUEST);
215     }
216     return;
217   }
218
219   // The request was tagged as an SDCH request, which means the server supplied
220   // a dictionary, and we advertised it in the request.  Some proxies will do
221   // very strange things to the request, or the response, so we have to handle
222   // them gracefully.
223
224   // If content encoding included SDCH, then everything is "relatively" fine.
225   if (!encoding_types->empty() &&
226       (FILTER_TYPE_SDCH == encoding_types->front())) {
227     // Some proxies (found currently in Argentina) strip the Content-Encoding
228     // text from "sdch,gzip" to a mere "sdch" without modifying the compressed
229     // payload.   To handle this gracefully, we simulate the "probably" deleted
230     // ",gzip" by appending a tentative gzip decode, which will default to a
231     // no-op pass through filter if it doesn't get gzip headers where expected.
232     if (1 == encoding_types->size()) {
233       encoding_types->push_back(FILTER_TYPE_GZIP_HELPING_SDCH);
234       SdchManager::SdchErrorRecovery(
235           SdchManager::OPTIONAL_GUNZIP_ENCODING_ADDED);
236     }
237     return;
238   }
239
240   // There are now several cases to handle for an SDCH request.  Foremost, if
241   // the outbound request was stripped so as not to advertise support for
242   // encodings, we might get back content with no encoding, or (for example)
243   // just gzip.  We have to be sure that any changes we make allow for such
244   // minimal coding to work.  That issue is why we use TENTATIVE filters if we
245   // add any, as those filters sniff the content, and act as pass-through
246   // filters if headers are not found.
247
248   // If the outbound GET is not modified, then the server will generally try to
249   // send us SDCH encoded content.  As that content returns, there are several
250   // corruptions of the header "content-encoding" that proxies may perform (and
251   // have been detected in the wild).  We already dealt with the a honest
252   // content encoding of "sdch,gzip" being corrupted into "sdch" with on change
253   // of the actual content.  Another common corruption is to either disscard
254   // the accurate content encoding, or to replace it with gzip only (again, with
255   // no change in actual content). The last observed corruption it to actually
256   // change the content, such as by re-gzipping it, and that may happen along
257   // with corruption of the stated content encoding (wow!).
258
259   // The one unresolved failure mode comes when we advertise a dictionary, and
260   // the server tries to *send* a gzipped file (not gzip encode content), and
261   // then we could do a gzip decode :-(. Since SDCH is only (currently)
262   // supported server side on paths that only send HTML content, this mode has
263   // never surfaced in the wild (and is unlikely to).
264   // We will gather a lot of stats as we perform the fixups
265   if (StartsWithASCII(mime_type, kTextHtml, false)) {
266     // Suspicious case: Advertised dictionary, but server didn't use sdch, and
267     // we're HTML tagged.
268     if (encoding_types->empty()) {
269       SdchManager::SdchErrorRecovery(
270           SdchManager::ADDED_CONTENT_ENCODING);
271     } else if (1 == encoding_types->size()) {
272       SdchManager::SdchErrorRecovery(
273           SdchManager::FIXED_CONTENT_ENCODING);
274     } else {
275       SdchManager::SdchErrorRecovery(
276           SdchManager::FIXED_CONTENT_ENCODINGS);
277     }
278   } else {
279     // Remarkable case!?!  We advertised an SDCH dictionary, content-encoding
280     // was not marked for SDCH processing: Why did the server suggest an SDCH
281     // dictionary in the first place??.  Also, the content isn't
282     // tagged as HTML, despite the fact that SDCH encoding is mostly likely for
283     // HTML: Did some anti-virus system strip this tag (sometimes they strip
284     // accept-encoding headers on the request)??  Does the content encoding not
285     // start with "text/html" for some other reason??  We'll report this as a
286     // fixup to a binary file, but it probably really is text/html (some how).
287     if (encoding_types->empty()) {
288       SdchManager::SdchErrorRecovery(
289           SdchManager::BINARY_ADDED_CONTENT_ENCODING);
290     } else if (1 == encoding_types->size()) {
291       SdchManager::SdchErrorRecovery(
292           SdchManager::BINARY_FIXED_CONTENT_ENCODING);
293     } else {
294       SdchManager::SdchErrorRecovery(
295           SdchManager::BINARY_FIXED_CONTENT_ENCODINGS);
296     }
297   }
298
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;
312 }
313
314 Filter::Filter()
315     : stream_buffer_(NULL),
316       stream_buffer_size_(0),
317       next_stream_data_(NULL),
318       stream_data_len_(0),
319       last_status_(FILTER_NEED_MORE_DATA) {}
320
321 Filter::FilterStatus Filter::CopyOut(char* dest_buffer, int* dest_len) {
322   int out_len;
323   int input_len = *dest_len;
324   *dest_len = 0;
325
326   if (0 == stream_data_len_)
327     return Filter::FILTER_NEED_MORE_DATA;
328
329   out_len = std::min(input_len, stream_data_len_);
330   memcpy(dest_buffer, next_stream_data_, out_len);
331   *dest_len += out_len;
332   stream_data_len_ -= out_len;
333   if (0 == stream_data_len_) {
334     next_stream_data_ = NULL;
335     return Filter::FILTER_NEED_MORE_DATA;
336   } else {
337     next_stream_data_ += out_len;
338     return Filter::FILTER_OK;
339   }
340 }
341
342 // static
343 Filter* Filter::InitGZipFilter(FilterType type_id, int buffer_size) {
344   scoped_ptr<GZipFilter> gz_filter(new GZipFilter());
345   gz_filter->InitBuffer(buffer_size);
346   return gz_filter->InitDecoding(type_id) ? gz_filter.release() : NULL;
347 }
348
349 // static
350 Filter* Filter::InitSdchFilter(FilterType type_id,
351                                const FilterContext& filter_context,
352                                int buffer_size) {
353   scoped_ptr<SdchFilter> sdch_filter(new SdchFilter(filter_context));
354   sdch_filter->InitBuffer(buffer_size);
355   return sdch_filter->InitDecoding(type_id) ? sdch_filter.release() : NULL;
356 }
357
358 // static
359 Filter* Filter::PrependNewFilter(FilterType type_id,
360                                  const FilterContext& filter_context,
361                                  int buffer_size,
362                                  Filter* filter_list) {
363   scoped_ptr<Filter> first_filter;  // Soon to be start of chain.
364   switch (type_id) {
365     case FILTER_TYPE_GZIP_HELPING_SDCH:
366     case FILTER_TYPE_DEFLATE:
367     case FILTER_TYPE_GZIP:
368       first_filter.reset(InitGZipFilter(type_id, buffer_size));
369       break;
370     case FILTER_TYPE_SDCH:
371     case FILTER_TYPE_SDCH_POSSIBLE:
372       if (SdchManager::Global() && SdchManager::sdch_enabled()) {
373         first_filter.reset(
374             InitSdchFilter(type_id, filter_context, buffer_size));
375       }
376       break;
377     default:
378       break;
379   }
380
381   if (!first_filter.get())
382     return NULL;
383
384   first_filter->next_filter_.reset(filter_list);
385   return first_filter.release();
386 }
387
388 void Filter::InitBuffer(int buffer_size) {
389   DCHECK(!stream_buffer());
390   DCHECK_GT(buffer_size, 0);
391   stream_buffer_ = new IOBuffer(buffer_size);
392   stream_buffer_size_ = buffer_size;
393 }
394
395 void Filter::PushDataIntoNextFilter() {
396   IOBuffer* next_buffer = next_filter_->stream_buffer();
397   int next_size = next_filter_->stream_buffer_size();
398   last_status_ = ReadFilteredData(next_buffer->data(), &next_size);
399   if (FILTER_ERROR != last_status_)
400     next_filter_->FlushStreamBuffer(next_size);
401 }
402
403 }  // namespace net