Home | History | Annotate | Download | only in base
      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.
      4 //
      5 // Filter performs filtering on data streams. Sample usage:
      6 //
      7 //   IStream* pre_filter_source;
      8 //   ...
      9 //   Filter* filter = Filter::Factory(filter_type, size);
     10 //   int pre_filter_data_len = filter->stream_buffer_size();
     11 //   pre_filter_source->read(filter->stream_buffer(), pre_filter_data_len);
     12 //
     13 //   filter->FlushStreamBuffer(pre_filter_data_len);
     14 //
     15 //   char post_filter_buf[kBufferSize];
     16 //   int post_filter_data_len = kBufferSize;
     17 //   filter->ReadFilteredData(post_filter_buf, &post_filter_data_len);
     18 //
     19 // To filter a data stream, the caller first gets filter's stream_buffer_
     20 // through its accessor and fills in stream_buffer_ with pre-filter data, next
     21 // calls FlushStreamBuffer to notify Filter, then calls ReadFilteredData
     22 // repeatedly to get all the filtered data. After all data have been fitlered
     23 // and read out, the caller may fill in stream_buffer_ again. This
     24 // WriteBuffer-Flush-Read cycle is repeated until reaching the end of data
     25 // stream.
     26 //
     27 // The lifetime of a Filter instance is completely controlled by its caller.
     28 
     29 #ifndef NET_BASE_FILTER_H__
     30 #define NET_BASE_FILTER_H__
     31 #pragma once
     32 
     33 #include <string>
     34 #include <vector>
     35 
     36 #include "base/basictypes.h"
     37 #include "base/gtest_prod_util.h"
     38 #include "base/memory/ref_counted.h"
     39 #include "base/memory/scoped_ptr.h"
     40 #include "base/time.h"
     41 
     42 class GURL;
     43 
     44 namespace net {
     45 
     46 class IOBuffer;
     47 
     48 //------------------------------------------------------------------------------
     49 // Define an interface class that allows access to contextual information
     50 // supplied by the owner of this filter.  In the case where there are a chain of
     51 // filters, there is only one owner of all the chained filters, and that context
     52 // is passed to the constructor of all those filters.  To be clear, the context
     53 // does NOT reflect the position in a chain, or the fact that there are prior
     54 // or later filters in a chain.
     55 class FilterContext {
     56  public:
     57   // Enum to control what histograms are emitted near end-of-life of this
     58   // instance.
     59   enum StatisticSelector {
     60     SDCH_DECODE,
     61     SDCH_PASSTHROUGH,
     62     SDCH_EXPERIMENT_DECODE,
     63     SDCH_EXPERIMENT_HOLDBACK,
     64   };
     65 
     66   virtual ~FilterContext();
     67 
     68   // What mime type was specified in the header for this data?
     69   // Only makes senses for some types of contexts, and returns false
     70   // when not applicable.
     71   virtual bool GetMimeType(std::string* mime_type) const = 0;
     72 
     73   // What URL was used to access this data?
     74   // Return false if gurl is not present.
     75   virtual bool GetURL(GURL* gurl) const = 0;
     76 
     77   // When was this data requested from a server?
     78   virtual base::Time GetRequestTime() const = 0;
     79 
     80   // Is data supplied from cache, or fresh across the net?
     81   virtual bool IsCachedContent() const = 0;
     82 
     83   // Is this a download?
     84   virtual bool IsDownload() const = 0;
     85 
     86   // Was this data flagged as a response to a request with an SDCH dictionary?
     87   virtual bool IsSdchResponse() const = 0;
     88 
     89   // How many bytes were read from the net or cache so far (and potentially
     90   // pushed into a filter for processing)?
     91   virtual int64 GetByteReadCount() const = 0;
     92 
     93   // What response code was received with the associated network transaction?
     94   // For example: 200 is ok.   4xx are error codes. etc.
     95   virtual int GetResponseCode() const = 0;
     96 
     97   // The following method forces the context to emit a specific set of
     98   // statistics as selected by the argument.
     99   virtual void RecordPacketStats(StatisticSelector statistic) const = 0;
    100 };
    101 
    102 //------------------------------------------------------------------------------
    103 class Filter {
    104  public:
    105   // Return values of function ReadFilteredData.
    106   enum FilterStatus {
    107     // Read filtered data successfully
    108     FILTER_OK,
    109     // Read filtered data successfully, and the data in the buffer has been
    110     // consumed by the filter, but more data is needed in order to continue
    111     // filtering.  At this point, the caller is free to reuse the filter
    112     // buffer to provide more data.
    113     FILTER_NEED_MORE_DATA,
    114     // Read filtered data successfully, and filter reaches the end of the data
    115     // stream.
    116     FILTER_DONE,
    117     // There is an error during filtering.
    118     FILTER_ERROR
    119   };
    120 
    121   // Specifies type of filters that can be created.
    122   enum FilterType {
    123     FILTER_TYPE_DEFLATE,
    124     FILTER_TYPE_GZIP,
    125     FILTER_TYPE_GZIP_HELPING_SDCH,  // Gzip possible, but pass through allowed.
    126     FILTER_TYPE_SDCH,
    127     FILTER_TYPE_SDCH_POSSIBLE,  // Sdch possible, but pass through allowed.
    128     FILTER_TYPE_UNSUPPORTED,
    129   };
    130 
    131   virtual ~Filter();
    132 
    133   // Creates a Filter object.
    134   // Parameters: Filter_types specifies the type of filter created;
    135   // filter_context allows filters to acquire additional details needed for
    136   // construction and operation, such as a specification of requisite input
    137   // buffer size.
    138   // If success, the function returns the pointer to the Filter object created.
    139   // If failed or a filter is not needed, the function returns NULL.
    140   //
    141   // Note: filter_types is an array of filter types (content encoding types as
    142   // provided in an HTTP header), which will be chained together serially to do
    143   // successive filtering of data.  The types in the vector are ordered based on
    144   // encoding order, and the filters are chained to operate in the reverse
    145   // (decoding) order. For example, types[0] = FILTER_TYPE_SDCH,
    146   // types[1] = FILTER_TYPE_GZIP will cause data to first be gunzip filtered,
    147   // and the resulting output from that filter will be sdch decoded.
    148   static Filter* Factory(const std::vector<FilterType>& filter_types,
    149                          const FilterContext& filter_context);
    150 
    151   // A simpler version of Factory() which creates a single, unchained
    152   // Filter of type FILTER_TYPE_GZIP, or NULL if the filter could not be
    153   // initialized.
    154   static Filter* GZipFactory();
    155 
    156   // External call to obtain data from this filter chain.  If ther is no
    157   // next_filter_, then it obtains data from this specific filter.
    158   FilterStatus ReadData(char* dest_buffer, int* dest_len);
    159 
    160   // Returns a pointer to the stream_buffer_.
    161   IOBuffer* stream_buffer() const { return stream_buffer_.get(); }
    162 
    163   // Returns the maximum size of stream_buffer_ in number of chars.
    164   int stream_buffer_size() const { return stream_buffer_size_; }
    165 
    166   // Returns the total number of chars remaining in stream_buffer_ to be
    167   // filtered.
    168   //
    169   // If the function returns 0 then all data has been filtered, and the caller
    170   // is safe to copy new data into stream_buffer_.
    171   int stream_data_len() const { return stream_data_len_; }
    172 
    173   // Flushes stream_buffer_ for next round of filtering. After copying data to
    174   // stream_buffer_, the caller should call this function to notify Filter to
    175   // start filtering. Then after this function is called, the caller can get
    176   // post-filtered data using ReadFilteredData. The caller must not write to
    177   // stream_buffer_ and call this function again before stream_buffer_ is
    178   // emptied out by ReadFilteredData.
    179   //
    180   // The input stream_data_len is the length (in number of chars) of valid
    181   // data in stream_buffer_. It can not be greater than stream_buffer_size_.
    182   // The function returns true if success, and false otherwise.
    183   bool FlushStreamBuffer(int stream_data_len);
    184 
    185   // Translate the text of a filter name (from Content-Encoding header) into a
    186   // FilterType.
    187   static FilterType ConvertEncodingToType(const std::string& filter_type);
    188 
    189   // Given a array of encoding_types, try to do some error recovery adjustment
    190   // to the list.  This includes handling known bugs in the Apache server (where
    191   // redundant gzip encoding is specified), as well as issues regarding SDCH
    192   // encoding, where various proxies and anti-virus products modify or strip the
    193   // encodings.  These fixups require context, which includes whether this
    194   // response was made to an SDCH request (i.e., an available dictionary was
    195   // advertised in the GET), as well as the mime type of the content.
    196   static void FixupEncodingTypes(const FilterContext& filter_context,
    197                                  std::vector<FilterType>* encoding_types);
    198 
    199  protected:
    200   friend class GZipUnitTest;
    201   friend class SdchFilterChainingTest;
    202 
    203   Filter();
    204 
    205   // Filters the data stored in stream_buffer_ and writes the output into the
    206   // dest_buffer passed in.
    207   //
    208   // Upon entry, *dest_len is the total size (in number of chars) of the
    209   // destination buffer. Upon exit, *dest_len is the actual number of chars
    210   // written into the destination buffer.
    211   //
    212   // This function will fail if there is no pre-filter data in the
    213   // stream_buffer_. On the other hand, *dest_len can be 0 upon successful
    214   // return. For example, a decoding filter may process some pre-filter data
    215   // but not produce output yet.
    216   virtual FilterStatus ReadFilteredData(char* dest_buffer, int* dest_len) = 0;
    217 
    218   // Copy pre-filter data directly to destination buffer without decoding.
    219   FilterStatus CopyOut(char* dest_buffer, int* dest_len);
    220 
    221   FilterStatus last_status() const { return last_status_; }
    222 
    223   // Buffer to hold the data to be filtered (the input queue).
    224   scoped_refptr<IOBuffer> stream_buffer_;
    225 
    226   // Maximum size of stream_buffer_ in number of chars.
    227   int stream_buffer_size_;
    228 
    229   // Pointer to the next data in stream_buffer_ to be filtered.
    230   char* next_stream_data_;
    231 
    232   // Total number of remaining chars in stream_buffer_ to be filtered.
    233   int stream_data_len_;
    234 
    235  private:
    236   // Allocates and initializes stream_buffer_ and stream_buffer_size_.
    237   void InitBuffer(int size);
    238 
    239   // A factory helper for creating filters for within a chain of potentially
    240   // multiple encodings.  If a chain of filters is created, then this may be
    241   // called multiple times during the filter creation process.  In most simple
    242   // cases, this is only called once. Returns NULL and cleans up (deleting
    243   // filter_list) if a new filter can't be constructed.
    244   static Filter* PrependNewFilter(FilterType type_id,
    245                                   const FilterContext& filter_context,
    246                                   int buffer_size,
    247                                   Filter* filter_list);
    248 
    249   // Helper methods for PrependNewFilter. If initialization is successful,
    250   // they return a fully initialized Filter. Otherwise, return NULL.
    251   static Filter* InitGZipFilter(FilterType type_id, int buffer_size);
    252   static Filter* InitSdchFilter(FilterType type_id,
    253                                 const FilterContext& filter_context,
    254                                 int buffer_size);
    255 
    256   // Helper function to empty our output into the next filter's input.
    257   void PushDataIntoNextFilter();
    258 
    259   // Constructs a filter with an internal buffer of the given size.
    260   // Only meant to be called by unit tests that need to control the buffer size.
    261   static Filter* FactoryForTests(const std::vector<FilterType>& filter_types,
    262                                  const FilterContext& filter_context,
    263                                  int buffer_size);
    264 
    265   // An optional filter to process output from this filter.
    266   scoped_ptr<Filter> next_filter_;
    267   // Remember what status or local filter last returned so we can better handle
    268   // chained filters.
    269   FilterStatus last_status_;
    270 
    271   DISALLOW_COPY_AND_ASSIGN(Filter);
    272 };
    273 
    274 }  // namespace net
    275 
    276 #endif  // NET_BASE_FILTER_H__
    277