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/filename_util_unsafe.h"
10#include "net/base/io_buffer.h"
11#include "net/base/mime_util.h"
12#include "net/filter/gzip_filter.h"
13#include "net/filter/sdch_filter.h"
14#include "net/url_request/url_request_context.h"
15#include "url/gurl.h"
16
17namespace {
18
19// Filter types (using canonical lower case only):
20const char kDeflate[]      = "deflate";
21const char kGZip[]         = "gzip";
22const char kXGZip[]        = "x-gzip";
23const char kSdch[]         = "sdch";
24// compress and x-compress are currently not supported.  If we decide to support
25// them, we'll need the same mime type compatibility hack we have for gzip.  For
26// more information, see Firefox's nsHttpChannel::ProcessNormal.
27
28// Mime types:
29const char kApplicationXGzip[]     = "application/x-gzip";
30const char kApplicationGzip[]      = "application/gzip";
31const char kApplicationXGunzip[]   = "application/x-gunzip";
32const char kTextHtml[]             = "text/html";
33
34// Buffer size allocated when de-compressing data.
35const int kFilterBufSize = 32 * 1024;
36
37}  // namespace
38
39namespace net {
40
41FilterContext::~FilterContext() {
42}
43
44Filter::~Filter() {}
45
46// static
47Filter* Filter::Factory(const std::vector<FilterType>& filter_types,
48                        const FilterContext& filter_context) {
49  if (filter_types.empty())
50    return NULL;
51
52  Filter* filter_list = NULL;  // Linked list of filters.
53  for (size_t i = 0; i < filter_types.size(); i++) {
54    filter_list = PrependNewFilter(filter_types[i], filter_context,
55                                   kFilterBufSize, filter_list);
56    if (!filter_list)
57      return NULL;
58  }
59  return filter_list;
60}
61
62// static
63Filter* Filter::GZipFactory() {
64  return InitGZipFilter(FILTER_TYPE_GZIP, kFilterBufSize);
65}
66
67// static
68Filter* Filter::FactoryForTests(const std::vector<FilterType>& filter_types,
69                                const FilterContext& filter_context,
70                                int buffer_size) {
71  if (filter_types.empty())
72    return NULL;
73
74  Filter* filter_list = NULL;  // Linked list of filters.
75  for (size_t i = 0; i < filter_types.size(); i++) {
76    filter_list = PrependNewFilter(filter_types[i], filter_context,
77                                   buffer_size, filter_list);
78    if (!filter_list)
79      return NULL;
80  }
81  return filter_list;
82}
83
84Filter::FilterStatus Filter::ReadData(char* dest_buffer, int* dest_len) {
85  const int dest_buffer_capacity = *dest_len;
86  if (last_status_ == FILTER_ERROR)
87    return last_status_;
88  if (!next_filter_.get())
89    return last_status_ = ReadFilteredData(dest_buffer, dest_len);
90  if (last_status_ == FILTER_NEED_MORE_DATA && !stream_data_len())
91    return next_filter_->ReadData(dest_buffer, dest_len);
92
93  do {
94    if (next_filter_->last_status() == FILTER_NEED_MORE_DATA) {
95      PushDataIntoNextFilter();
96      if (FILTER_ERROR == last_status_)
97        return FILTER_ERROR;
98    }
99    *dest_len = dest_buffer_capacity;  // Reset the input/output parameter.
100    next_filter_->ReadData(dest_buffer, dest_len);
101    if (FILTER_NEED_MORE_DATA == last_status_)
102        return next_filter_->last_status();
103
104    // In the case where this filter has data internally, and is indicating such
105    // with a last_status_ of FILTER_OK, but at the same time the next filter in
106    // the chain indicated it FILTER_NEED_MORE_DATA, we have to be cautious
107    // about confusing the caller.  The API confusion can appear if we return
108    // FILTER_OK (suggesting we have more data in aggregate), but yet we don't
109    // populate our output buffer.  When that is the case, we need to
110    // alternately call our filter element, and the next_filter element until we
111    // get out of this state (by pumping data into the next filter until it
112    // outputs data, or it runs out of data and reports that it NEED_MORE_DATA.)
113  } while (FILTER_OK == last_status_ &&
114           FILTER_NEED_MORE_DATA == next_filter_->last_status() &&
115           0 == *dest_len);
116
117  if (next_filter_->last_status() == FILTER_ERROR)
118    return FILTER_ERROR;
119  return FILTER_OK;
120}
121
122bool Filter::FlushStreamBuffer(int stream_data_len) {
123  DCHECK_LE(stream_data_len, stream_buffer_size_);
124  if (stream_data_len <= 0 || stream_data_len > stream_buffer_size_)
125    return false;
126
127  DCHECK(stream_buffer());
128  // Bail out if there is more data in the stream buffer to be filtered.
129  if (!stream_buffer() || stream_data_len_)
130    return false;
131
132  next_stream_data_ = stream_buffer()->data();
133  stream_data_len_ = stream_data_len;
134  return true;
135}
136
137// static
138Filter::FilterType Filter::ConvertEncodingToType(
139    const std::string& filter_type) {
140  FilterType type_id;
141  if (LowerCaseEqualsASCII(filter_type, kDeflate)) {
142    type_id = FILTER_TYPE_DEFLATE;
143  } else if (LowerCaseEqualsASCII(filter_type, kGZip) ||
144             LowerCaseEqualsASCII(filter_type, kXGZip)) {
145    type_id = FILTER_TYPE_GZIP;
146  } else if (LowerCaseEqualsASCII(filter_type, kSdch)) {
147    type_id = FILTER_TYPE_SDCH;
148  } else {
149    // Note we also consider "identity" and "uncompressed" UNSUPPORTED as
150    // filter should be disabled in such cases.
151    type_id = FILTER_TYPE_UNSUPPORTED;
152  }
153  return type_id;
154}
155
156// static
157void Filter::FixupEncodingTypes(
158    const FilterContext& filter_context,
159    std::vector<FilterType>* encoding_types) {
160  std::string mime_type;
161  bool success = filter_context.GetMimeType(&mime_type);
162  DCHECK(success || mime_type.empty());
163
164  if ((1 == encoding_types->size()) &&
165      (FILTER_TYPE_GZIP == encoding_types->front())) {
166    if (LowerCaseEqualsASCII(mime_type, kApplicationXGzip) ||
167        LowerCaseEqualsASCII(mime_type, kApplicationGzip) ||
168        LowerCaseEqualsASCII(mime_type, kApplicationXGunzip))
169      // The server has told us that it sent us gziped content with a gzip
170      // content encoding.  Sadly, Apache mistakenly sets these headers for all
171      // .gz files.  We match Firefox's nsHttpChannel::ProcessNormal and ignore
172      // the Content-Encoding here.
173      encoding_types->clear();
174
175    GURL url;
176    std::string disposition;
177    success = filter_context.GetURL(&url);
178    DCHECK(success);
179    filter_context.GetContentDisposition(&disposition);
180    // Don't supply a MIME type here, since that may cause disk IO.
181    base::FilePath::StringType extension =
182        GenerateFileExtensionUnsafe(url, disposition, "UTF-8", "", "", "");
183
184    if (filter_context.IsDownload()) {
185      // We don't want to decompress gzipped files when the user explicitly
186      // asks to download them.
187      // For the case of svgz files, we use the extension to distinguish
188      // between svgz files and svg files compressed with gzip by the server.
189      // When viewing a .svgz file, we need to uncompress it, but we don't
190      // want to do that when downloading.
191      // See Firefox's nonDecodableExtensions in nsExternalHelperAppService.cpp
192      if (EndsWith(extension, FILE_PATH_LITERAL(".gz"), false) ||
193          LowerCaseEqualsASCII(extension, ".tgz") ||
194          LowerCaseEqualsASCII(extension, ".svgz"))
195        encoding_types->clear();
196    } else {
197      // When the user does not explicitly ask to download a file, if we get a
198      // supported mime type, then we attempt to decompress in order to view it.
199      // However, if it's not a supported mime type, then we will attempt to
200      // download it, and in that case, don't decompress .gz/.tgz files.
201      if ((EndsWith(extension, FILE_PATH_LITERAL(".gz"), false) ||
202           LowerCaseEqualsASCII(extension, ".tgz")) &&
203          !IsSupportedMimeType(mime_type))
204        encoding_types->clear();
205    }
206  }
207
208  // If the request was for SDCH content, then we might need additional fixups.
209  if (!filter_context.SdchResponseExpected()) {
210    // It was not an SDCH request, so we'll just record stats.
211    if (1 < encoding_types->size()) {
212      // Multiple filters were intended to only be used for SDCH (thus far!)
213      SdchManager::SdchErrorRecovery(
214          SdchManager::MULTIENCODING_FOR_NON_SDCH_REQUEST);
215    }
216    if ((1 == encoding_types->size()) &&
217        (FILTER_TYPE_SDCH == encoding_types->front())) {
218        SdchManager::SdchErrorRecovery(
219            SdchManager::SDCH_CONTENT_ENCODE_FOR_NON_SDCH_REQUEST);
220    }
221    return;
222  }
223
224  // The request was tagged as an SDCH request, which means the server supplied
225  // a dictionary, and we advertised it in the request.  Some proxies will do
226  // very strange things to the request, or the response, so we have to handle
227  // them gracefully.
228
229  // If content encoding included SDCH, then everything is "relatively" fine.
230  if (!encoding_types->empty() &&
231      (FILTER_TYPE_SDCH == encoding_types->front())) {
232    // Some proxies (found currently in Argentina) strip the Content-Encoding
233    // text from "sdch,gzip" to a mere "sdch" without modifying the compressed
234    // payload.   To handle this gracefully, we simulate the "probably" deleted
235    // ",gzip" by appending a tentative gzip decode, which will default to a
236    // no-op pass through filter if it doesn't get gzip headers where expected.
237    if (1 == encoding_types->size()) {
238      encoding_types->push_back(FILTER_TYPE_GZIP_HELPING_SDCH);
239      SdchManager::SdchErrorRecovery(
240          SdchManager::OPTIONAL_GUNZIP_ENCODING_ADDED);
241    }
242    return;
243  }
244
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.
252
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!).
263
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 (StartsWithASCII(mime_type, kTextHtml, false)) {
271    // Suspicious case: Advertised dictionary, but server didn't use sdch, and
272    // we're HTML tagged.
273    if (encoding_types->empty()) {
274      SdchManager::SdchErrorRecovery(
275          SdchManager::ADDED_CONTENT_ENCODING);
276    } else if (1 == encoding_types->size()) {
277      SdchManager::SdchErrorRecovery(
278          SdchManager::FIXED_CONTENT_ENCODING);
279    } else {
280      SdchManager::SdchErrorRecovery(
281          SdchManager::FIXED_CONTENT_ENCODINGS);
282    }
283  } else {
284    // Remarkable case!?!  We advertised an SDCH dictionary, content-encoding
285    // was not marked for SDCH processing: Why did the server suggest an SDCH
286    // dictionary in the first place??.  Also, the content isn't
287    // tagged as HTML, despite the fact that SDCH encoding is mostly likely for
288    // HTML: Did some anti-virus system strip this tag (sometimes they strip
289    // accept-encoding headers on the request)??  Does the content encoding not
290    // start with "text/html" for some other reason??  We'll report this as a
291    // fixup to a binary file, but it probably really is text/html (some how).
292    if (encoding_types->empty()) {
293      SdchManager::SdchErrorRecovery(
294          SdchManager::BINARY_ADDED_CONTENT_ENCODING);
295    } else if (1 == encoding_types->size()) {
296      SdchManager::SdchErrorRecovery(
297          SdchManager::BINARY_FIXED_CONTENT_ENCODING);
298    } else {
299      SdchManager::SdchErrorRecovery(
300          SdchManager::BINARY_FIXED_CONTENT_ENCODINGS);
301    }
302  }
303
304  // Leave the existing encoding type to be processed first, and add our
305  // tentative decodings to be done afterwards.  Vodaphone UK reportedyl will
306  // perform a second layer of gzip encoding atop the server's sdch,gzip
307  // encoding, and then claim that the content encoding is a mere gzip.  As a
308  // result we'll need (in that case) to do the gunzip, plus our tentative
309  // gunzip and tentative SDCH decoding.
310  // This approach nicely handles the empty() list as well, and should work with
311  // other (as yet undiscovered) proxies the choose to re-compressed with some
312  // other encoding (such as bzip2, etc.).
313  encoding_types->insert(encoding_types->begin(),
314                         FILTER_TYPE_GZIP_HELPING_SDCH);
315  encoding_types->insert(encoding_types->begin(), FILTER_TYPE_SDCH_POSSIBLE);
316  return;
317}
318
319Filter::Filter()
320    : stream_buffer_(NULL),
321      stream_buffer_size_(0),
322      next_stream_data_(NULL),
323      stream_data_len_(0),
324      last_status_(FILTER_NEED_MORE_DATA) {}
325
326Filter::FilterStatus Filter::CopyOut(char* dest_buffer, int* dest_len) {
327  int out_len;
328  int input_len = *dest_len;
329  *dest_len = 0;
330
331  if (0 == stream_data_len_)
332    return Filter::FILTER_NEED_MORE_DATA;
333
334  out_len = std::min(input_len, stream_data_len_);
335  memcpy(dest_buffer, next_stream_data_, out_len);
336  *dest_len += out_len;
337  stream_data_len_ -= out_len;
338  if (0 == stream_data_len_) {
339    next_stream_data_ = NULL;
340    return Filter::FILTER_NEED_MORE_DATA;
341  } else {
342    next_stream_data_ += out_len;
343    return Filter::FILTER_OK;
344  }
345}
346
347// static
348Filter* Filter::InitGZipFilter(FilterType type_id, int buffer_size) {
349  scoped_ptr<GZipFilter> gz_filter(new GZipFilter());
350  gz_filter->InitBuffer(buffer_size);
351  return gz_filter->InitDecoding(type_id) ? gz_filter.release() : NULL;
352}
353
354// static
355Filter* Filter::InitSdchFilter(FilterType type_id,
356                               const FilterContext& filter_context,
357                               int buffer_size) {
358  scoped_ptr<SdchFilter> sdch_filter(new SdchFilter(filter_context));
359  sdch_filter->InitBuffer(buffer_size);
360  return sdch_filter->InitDecoding(type_id) ? sdch_filter.release() : NULL;
361}
362
363// static
364Filter* Filter::PrependNewFilter(FilterType type_id,
365                                 const FilterContext& filter_context,
366                                 int buffer_size,
367                                 Filter* filter_list) {
368  scoped_ptr<Filter> first_filter;  // Soon to be start of chain.
369  switch (type_id) {
370    case FILTER_TYPE_GZIP_HELPING_SDCH:
371    case FILTER_TYPE_DEFLATE:
372    case FILTER_TYPE_GZIP:
373      first_filter.reset(InitGZipFilter(type_id, buffer_size));
374      break;
375    case FILTER_TYPE_SDCH:
376    case FILTER_TYPE_SDCH_POSSIBLE:
377      if (filter_context.GetURLRequestContext()->sdch_manager() &&
378          SdchManager::sdch_enabled()) {
379        first_filter.reset(
380            InitSdchFilter(type_id, filter_context, buffer_size));
381      }
382      break;
383    default:
384      break;
385  }
386
387  if (!first_filter.get())
388    return NULL;
389
390  first_filter->next_filter_.reset(filter_list);
391  return first_filter.release();
392}
393
394void Filter::InitBuffer(int buffer_size) {
395  DCHECK(!stream_buffer());
396  DCHECK_GT(buffer_size, 0);
397  stream_buffer_ = new IOBuffer(buffer_size);
398  stream_buffer_size_ = buffer_size;
399}
400
401void Filter::PushDataIntoNextFilter() {
402  IOBuffer* next_buffer = next_filter_->stream_buffer();
403  int next_size = next_filter_->stream_buffer_size();
404  last_status_ = ReadFilteredData(next_buffer->data(), &next_size);
405  if (FILTER_ERROR != last_status_)
406    next_filter_->FlushStreamBuffer(next_size);
407}
408
409}  // namespace net
410