[Android WebView] Fix webview perf bot switchover to use org.chromium.webview_shell...
[chromium-blink-merge.git] / net / filter / filter.h
blob1904a8cdbb957be08b6baf3ef509d56a130a31ec
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 // 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);
13 // filter->FlushStreamBuffer(pre_filter_data_len);
15 // char post_filter_buf[kBufferSize];
16 // int post_filter_data_len = kBufferSize;
17 // filter->ReadFilteredData(post_filter_buf, &post_filter_data_len);
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 filtered
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.
27 // A return of FILTER_OK from ReadData() means that more data is
28 // available to a future ReadData() call and data may not be written
29 // into stream_buffer(). A return of FILTER_NEED_MORE_DATA from ReadData()
30 // indicates that no data will be forthcoming from the filter until
31 // it receives more input data, and that the buffer at
32 // stream_buffer() may be written to.
34 // The filter being complete (no more data to provide) may be indicated
35 // by either returning FILTER_DONE or by returning FILTER_OK and indicating
36 // zero bytes output; consumers understand both those signals. Consumers
37 // are responsible for not calling ReadData() on a filter after one of these
38 // signals have been returned. Note that some filters may never signal that
39 // they are done (e.g. a pass-through filter will always
40 // say FILTER_NEED_MORE_DATA), so the consumer will also need to
41 // recognize the state of |no_more_input_data_available &&
42 // filter->stream_data_len() == 0| as FILTER_DONE.
44 // The lifetime of a Filter instance is completely controlled by its caller.
46 #ifndef NET_FILTER_FILTER_H__
47 #define NET_FILTER_FILTER_H__
49 #include <string>
50 #include <vector>
52 #include "base/basictypes.h"
53 #include "base/gtest_prod_util.h"
54 #include "base/memory/ref_counted.h"
55 #include "base/memory/scoped_ptr.h"
56 #include "base/time/time.h"
57 #include "net/base/net_export.h"
58 #include "net/base/sdch_manager.h"
60 class GURL;
62 namespace net {
64 class BoundNetLog;
65 class IOBuffer;
66 class URLRequestContext;
68 //------------------------------------------------------------------------------
69 // Define an interface class that allows access to contextual information
70 // supplied by the owner of this filter. In the case where there are a chain of
71 // filters, there is only one owner of all the chained filters, and that context
72 // is passed to the constructor of all those filters. To be clear, the context
73 // does NOT reflect the position in a chain, or the fact that there are prior
74 // or later filters in a chain.
76 // TODO(rdsmith): FilterContext is a grab-bag of methods which may or may
77 // not be relevant for any particular filter, and it's getting worse over
78 // time. In addition, it only supports two filters, SDCH and gzip.
79 // It would make more sense to implement FilterContext as a
80 // base::SupportsUserData structure to which filter-specific information
81 // could be added by whatever the ultimate consumer of the filter chain is,
82 // and a particular filter (if included) could access that information.
83 class NET_EXPORT_PRIVATE FilterContext {
84 public:
85 // Enum to control what histograms are emitted near end-of-life of this
86 // instance.
87 enum StatisticSelector {
88 SDCH_DECODE,
89 SDCH_PASSTHROUGH,
90 SDCH_EXPERIMENT_DECODE,
91 SDCH_EXPERIMENT_HOLDBACK,
94 virtual ~FilterContext();
96 // What mime type was specified in the header for this data?
97 // Only makes senses for some types of contexts, and returns false
98 // when not applicable.
99 virtual bool GetMimeType(std::string* mime_type) const = 0;
101 // What URL was used to access this data?
102 // Return false if gurl is not present.
103 virtual bool GetURL(GURL* gurl) const = 0;
105 // When was this data requested from a server?
106 virtual base::Time GetRequestTime() const = 0;
108 // Is data supplied from cache, or fresh across the net?
109 virtual bool IsCachedContent() const = 0;
111 // Was this data flagged as a response to a request with an SDCH dictionary?
112 virtual SdchManager::DictionarySet* SdchDictionariesAdvertised() const = 0;
114 // How many bytes were read from the net or cache so far (and potentially
115 // pushed into a filter for processing)?
116 virtual int64 GetByteReadCount() const = 0;
118 // What response code was received with the associated network transaction?
119 // For example: 200 is ok. 4xx are error codes. etc.
120 virtual int GetResponseCode() const = 0;
122 // The URLRequestContext associated with the request.
123 virtual const URLRequestContext* GetURLRequestContext() const = 0;
125 // The following method forces the context to emit a specific set of
126 // statistics as selected by the argument.
127 virtual void RecordPacketStats(StatisticSelector statistic) const = 0;
129 // The BoundNetLog of the associated request.
130 virtual const BoundNetLog& GetNetLog() const = 0;
133 //------------------------------------------------------------------------------
134 class NET_EXPORT_PRIVATE Filter {
135 public:
136 // Return values of function ReadFilteredData.
137 enum FilterStatus {
138 // Read filtered data successfully
139 FILTER_OK,
140 // Read filtered data successfully, and the data in the buffer has been
141 // consumed by the filter, but more data is needed in order to continue
142 // filtering. At this point, the caller is free to reuse the filter
143 // buffer to provide more data.
144 FILTER_NEED_MORE_DATA,
145 // Read filtered data successfully, and filter reaches the end of the data
146 // stream.
147 FILTER_DONE,
148 // There is an error during filtering.
149 FILTER_ERROR
152 // Specifies type of filters that can be created.
153 enum FilterType {
154 FILTER_TYPE_DEFLATE,
155 FILTER_TYPE_GZIP,
156 FILTER_TYPE_GZIP_HELPING_SDCH, // Gzip possible, but pass through allowed.
157 FILTER_TYPE_SDCH,
158 FILTER_TYPE_SDCH_POSSIBLE, // Sdch possible, but pass through allowed.
159 FILTER_TYPE_UNSUPPORTED,
162 virtual ~Filter();
164 // Creates a Filter object.
165 // Parameters: Filter_types specifies the type of filter created;
166 // filter_context allows filters to acquire additional details needed for
167 // construction and operation, such as a specification of requisite input
168 // buffer size.
169 // If success, the function returns the pointer to the Filter object created.
170 // If failed or a filter is not needed, the function returns NULL.
172 // Note: filter_types is an array of filter types (content encoding types as
173 // provided in an HTTP header), which will be chained together serially to do
174 // successive filtering of data. The types in the vector are ordered based on
175 // encoding order, and the filters are chained to operate in the reverse
176 // (decoding) order. For example, types[0] = FILTER_TYPE_SDCH,
177 // types[1] = FILTER_TYPE_GZIP will cause data to first be gunzip filtered,
178 // and the resulting output from that filter will be sdch decoded.
179 static Filter* Factory(const std::vector<FilterType>& filter_types,
180 const FilterContext& filter_context);
182 // A simpler version of Factory() which creates a single, unchained
183 // Filter of type FILTER_TYPE_GZIP, or NULL if the filter could not be
184 // initialized.
185 static Filter* GZipFactory();
187 // External call to obtain data from this filter chain. If ther is no
188 // next_filter_, then it obtains data from this specific filter.
189 FilterStatus ReadData(char* dest_buffer, int* dest_len);
191 // Returns a pointer to the stream_buffer_.
192 IOBuffer* stream_buffer() const { return stream_buffer_.get(); }
194 // Returns the maximum size of stream_buffer_ in number of chars.
195 int stream_buffer_size() const { return stream_buffer_size_; }
197 // Returns the total number of chars remaining in stream_buffer_ to be
198 // filtered.
200 // If the function returns 0 then all data has been filtered, and the caller
201 // is safe to copy new data into stream_buffer_.
202 int stream_data_len() const { return stream_data_len_; }
204 // Flushes stream_buffer_ for next round of filtering. After copying data to
205 // stream_buffer_, the caller should call this function to notify Filter to
206 // start filtering. Then after this function is called, the caller can get
207 // post-filtered data using ReadFilteredData. The caller must not write to
208 // stream_buffer_ and call this function again before stream_buffer_ is
209 // emptied out by ReadFilteredData.
211 // The input stream_data_len is the length (in number of chars) of valid
212 // data in stream_buffer_. It can not be greater than stream_buffer_size_.
213 // The function returns true if success, and false otherwise.
214 bool FlushStreamBuffer(int stream_data_len);
216 // Translate the text of a filter name (from Content-Encoding header) into a
217 // FilterType.
218 static FilterType ConvertEncodingToType(const std::string& filter_type);
220 // Given a array of encoding_types, try to do some error recovery adjustment
221 // to the list. This includes handling known bugs in the Apache server (where
222 // redundant gzip encoding is specified), as well as issues regarding SDCH
223 // encoding, where various proxies and anti-virus products modify or strip the
224 // encodings. These fixups require context, which includes whether this
225 // response was made to an SDCH request (i.e., an available dictionary was
226 // advertised in the GET), as well as the mime type of the content.
227 static void FixupEncodingTypes(const FilterContext& filter_context,
228 std::vector<FilterType>* encoding_types);
230 // Returns a string describing the FilterTypes implemented by this filter.
231 std::string OrderedFilterList() const;
233 protected:
234 friend class GZipUnitTest;
235 friend class SdchFilterChainingTest;
236 FRIEND_TEST_ALL_PREFIXES(FilterTest, ThreeFilterChain);
238 explicit Filter(FilterType type_id);
240 // Filters the data stored in stream_buffer_ and writes the output into the
241 // dest_buffer passed in.
243 // Upon entry, *dest_len is the total size (in number of chars) of the
244 // destination buffer. Upon exit, *dest_len is the actual number of chars
245 // written into the destination buffer.
247 // This function will fail if there is no pre-filter data in the
248 // stream_buffer_. On the other hand, *dest_len can be 0 upon successful
249 // return. For example, a decoding filter may process some pre-filter data
250 // but not produce output yet.
251 virtual FilterStatus ReadFilteredData(char* dest_buffer, int* dest_len) = 0;
253 // Copy pre-filter data directly to destination buffer without decoding.
254 FilterStatus CopyOut(char* dest_buffer, int* dest_len);
256 FilterStatus last_status() const { return last_status_; }
258 // Buffer to hold the data to be filtered (the input queue).
259 scoped_refptr<IOBuffer> stream_buffer_;
261 // Maximum size of stream_buffer_ in number of chars.
262 int stream_buffer_size_;
264 // Pointer to the next data in stream_buffer_ to be filtered.
265 char* next_stream_data_;
267 // Total number of remaining chars in stream_buffer_ to be filtered.
268 int stream_data_len_;
270 private:
271 // Allocates and initializes stream_buffer_ and stream_buffer_size_.
272 void InitBuffer(int size);
274 // A factory helper for creating filters for within a chain of potentially
275 // multiple encodings. If a chain of filters is created, then this may be
276 // called multiple times during the filter creation process. In most simple
277 // cases, this is only called once. Returns NULL and cleans up (deleting
278 // filter_list) if a new filter can't be constructed.
279 static Filter* PrependNewFilter(FilterType type_id,
280 const FilterContext& filter_context,
281 int buffer_size,
282 Filter* filter_list);
284 // Helper methods for PrependNewFilter. If initialization is successful,
285 // they return a fully initialized Filter. Otherwise, return NULL.
286 static Filter* InitGZipFilter(FilterType type_id, int buffer_size);
287 static Filter* InitSdchFilter(FilterType type_id,
288 const FilterContext& filter_context,
289 int buffer_size);
291 // Helper function to empty our output into the next filter's input.
292 void PushDataIntoNextFilter();
294 // Constructs a filter with an internal buffer of the given size.
295 // Only meant to be called by unit tests that need to control the buffer size.
296 static Filter* FactoryForTests(const std::vector<FilterType>& filter_types,
297 const FilterContext& filter_context,
298 int buffer_size);
300 // An optional filter to process output from this filter.
301 scoped_ptr<Filter> next_filter_;
303 // Remember what status or local filter last returned so we can better handle
304 // chained filters.
305 FilterStatus last_status_;
307 // The filter type this filter was constructed from.
308 FilterType type_id_;
310 DISALLOW_COPY_AND_ASSIGN(Filter);
313 } // namespace net
315 #endif // NET_FILTER_FILTER_H__