Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / base / sdch_manager.h
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 #ifndef NET_BASE_SDCH_MANAGER_H_
6 #define NET_BASE_SDCH_MANAGER_H_
7
8 #include <map>
9 #include <set>
10 #include <string>
11
12 #include "base/gtest_prod_util.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/time/time.h"
18 #include "net/base/net_export.h"
19 #include "url/gurl.h"
20
21 namespace net {
22
23 class SdchObserver;
24
25 // Provides global database of differential decompression dictionaries for the
26 // SDCH filter (processes sdch enconded content).
27 //
28 // The SdchManager maintains a collection of memory resident dictionaries. It
29 // can find a dictionary (based on a server specification of a hash), store a
30 // dictionary, and make judgements about what URLs can use, set, etc. a
31 // dictionary.
32
33 // These dictionaries are acquired over the net, and include a header
34 // (containing metadata) as well as a VCDIFF dictionary (for use by a VCDIFF
35 // module) to decompress data.
36 class NET_EXPORT SdchManager {
37  public:
38   // A list of errors that appeared and were either resolved, or used to turn
39   // off sdch encoding.
40   enum ProblemCodes {
41     MIN_PROBLEM_CODE,
42
43     // Content-encoding correction problems.
44     ADDED_CONTENT_ENCODING = 1,
45     FIXED_CONTENT_ENCODING = 2,
46     FIXED_CONTENT_ENCODINGS = 3,
47
48     // Content decoding errors.
49     DECODE_HEADER_ERROR = 4,
50     DECODE_BODY_ERROR = 5,
51
52     // More content-encoding correction problems.
53     OPTIONAL_GUNZIP_ENCODING_ADDED = 6,
54
55     // Content encoding correction when we're not even tagged as HTML!?!
56     BINARY_ADDED_CONTENT_ENCODING = 7,
57     BINARY_FIXED_CONTENT_ENCODING = 8,
58     BINARY_FIXED_CONTENT_ENCODINGS = 9,
59
60     // Dictionary selection for use problems.
61     DICTIONARY_FOUND_HAS_WRONG_DOMAIN = 10,
62     DICTIONARY_FOUND_HAS_WRONG_PORT_LIST = 11,
63     DICTIONARY_FOUND_HAS_WRONG_PATH = 12,
64     DICTIONARY_FOUND_HAS_WRONG_SCHEME = 13,
65     DICTIONARY_HASH_NOT_FOUND = 14,
66     DICTIONARY_HASH_MALFORMED = 15,
67
68     // Dictionary saving problems.
69     DICTIONARY_HAS_NO_HEADER = 20,
70     DICTIONARY_HEADER_LINE_MISSING_COLON = 21,
71     DICTIONARY_MISSING_DOMAIN_SPECIFIER = 22,
72     DICTIONARY_SPECIFIES_TOP_LEVEL_DOMAIN = 23,
73     DICTIONARY_DOMAIN_NOT_MATCHING_SOURCE_URL = 24,
74     DICTIONARY_PORT_NOT_MATCHING_SOURCE_URL = 25,
75     DICTIONARY_HAS_NO_TEXT = 26,
76     DICTIONARY_REFERER_URL_HAS_DOT_IN_PREFIX = 27,
77
78     // Dictionary loading problems.
79     DICTIONARY_LOAD_ATTEMPT_FROM_DIFFERENT_HOST = 30,
80     DICTIONARY_SELECTED_FOR_SSL = 31,
81     DICTIONARY_ALREADY_LOADED = 32,
82     DICTIONARY_SELECTED_FROM_NON_HTTP = 33,
83     DICTIONARY_IS_TOO_LARGE= 34,
84     DICTIONARY_COUNT_EXCEEDED = 35,
85     DICTIONARY_ALREADY_SCHEDULED_TO_DOWNLOAD = 36,
86     DICTIONARY_ALREADY_TRIED_TO_DOWNLOAD = 37,
87     DICTIONARY_FETCH_READ_FAILED = 38,
88
89     // Failsafe hack.
90     ATTEMPT_TO_DECODE_NON_HTTP_DATA = 40,
91
92
93     // Content-Encoding problems detected, with no action taken.
94     MULTIENCODING_FOR_NON_SDCH_REQUEST = 50,
95     SDCH_CONTENT_ENCODE_FOR_NON_SDCH_REQUEST = 51,
96
97     // Dictionary manager issues.
98     DOMAIN_BLACKLIST_INCLUDES_TARGET = 61,
99
100     // Problematic decode recovery methods.
101     META_REFRESH_RECOVERY = 70,            // Dictionary not found.
102     // defunct =  71, // Almost the same as META_REFRESH_UNSUPPORTED.
103     // defunct = 72,  // Almost the same as CACHED_META_REFRESH_UNSUPPORTED.
104     // defunct = 73,  // PASSING_THROUGH_NON_SDCH plus
105                       // RESPONSE_TENTATIVE_SDCH in ../filter/sdch_filter.cc.
106     META_REFRESH_UNSUPPORTED = 74,         // Unrecoverable error.
107     CACHED_META_REFRESH_UNSUPPORTED = 75,  // As above, but pulled from cache.
108     PASSING_THROUGH_NON_SDCH = 76,  // Tagged sdch but missing dictionary-hash.
109     INCOMPLETE_SDCH_CONTENT = 77,   // Last window was not completely decoded.
110     PASS_THROUGH_404_CODE = 78,     // URL not found message passing through.
111
112     // This next report is very common, and not really an error scenario, but
113     // it exercises the error recovery logic.
114     PASS_THROUGH_OLD_CACHED = 79,   // Back button got pre-SDCH cached content.
115
116     // Common decoded recovery methods.
117     META_REFRESH_CACHED_RECOVERY = 80,  // Probably startup tab loading.
118     // defunct = 81, // Now tracked by ResponseCorruptionDetectionCause histo.
119
120     // Non SDCH problems, only accounted for to make stat counting complete
121     // (i.e., be able to be sure all dictionary advertisements are accounted
122     // for).
123
124     UNFLUSHED_CONTENT = 90,    // Possible error in filter chaining.
125     // defunct = 91,           // MISSING_TIME_STATS (Should never happen.)
126     CACHE_DECODED = 92,        // No timing stats recorded.
127     // defunct = 93,           // OVER_10_MINUTES (No timing stats recorded.)
128     UNINITIALIZED = 94,        // Filter never even got initialized.
129     PRIOR_TO_DICTIONARY = 95,  // We hadn't even parsed a dictionary selector.
130     DECODE_ERROR = 96,         // Something went wrong during decode.
131
132     // Problem during the latency test.
133     LATENCY_TEST_DISALLOWED = 100,  // SDCH now failing, but it worked before!
134
135     MAX_PROBLEM_CODE  // Used to bound histogram.
136   };
137
138   // Use the following static limits to block DOS attacks until we implement
139   // a cached dictionary evicition strategy.
140   static const size_t kMaxDictionarySize;
141   static const size_t kMaxDictionaryCount;
142
143   // There is one instance of |Dictionary| for each memory-cached SDCH
144   // dictionary.
145   class NET_EXPORT_PRIVATE Dictionary : public base::RefCounted<Dictionary> {
146    public:
147     // Sdch filters can get our text to use in decoding compressed data.
148     const std::string& text() const { return text_; }
149
150    private:
151     friend class base::RefCounted<Dictionary>;
152     friend class SdchManager;  // Only manager can construct an instance.
153     FRIEND_TEST_ALL_PREFIXES(SdchManagerTest, PathMatch);
154
155     // Construct a vc-diff usable dictionary from the dictionary_text starting
156     // at the given offset. The supplied client_hash should be used to
157     // advertise the dictionary's availability relative to the suppplied URL.
158     Dictionary(const std::string& dictionary_text,
159                size_t offset,
160                const std::string& client_hash,
161                const GURL& url,
162                const std::string& domain,
163                const std::string& path,
164                const base::Time& expiration,
165                const std::set<int>& ports);
166     virtual ~Dictionary();
167
168     const GURL& url() const { return url_; }
169     const std::string& client_hash() const { return client_hash_; }
170
171     // Security method to check if we can advertise this dictionary for use
172     // if the |target_url| returns SDCH compressed data.
173     bool CanAdvertise(const GURL& target_url);
174
175     // Security methods to check if we can establish a new dictionary with the
176     // given data, that arrived in response to get of dictionary_url.
177     static bool CanSet(const std::string& domain, const std::string& path,
178                        const std::set<int>& ports, const GURL& dictionary_url);
179
180     // Security method to check if we can use a dictionary to decompress a
181     // target that arrived with a reference to this dictionary.
182     bool CanUse(const GURL& referring_url);
183
184     // Compare paths to see if they "match" for dictionary use.
185     static bool PathMatch(const std::string& path,
186                           const std::string& restriction);
187
188     // Compare domains to see if the "match" for dictionary use.
189     static bool DomainMatch(const GURL& url, const std::string& restriction);
190
191
192     // The actual text of the dictionary.
193     std::string text_;
194
195     // Part of the hash of text_ that the client uses to advertise the fact that
196     // it has a specific dictionary pre-cached.
197     std::string client_hash_;
198
199     // The GURL that arrived with the text_ in a URL request to specify where
200     // this dictionary may be used.
201     const GURL url_;
202
203     // Metadate "headers" in before dictionary text contained the following:
204     // Each dictionary payload consists of several headers, followed by the text
205     // of the dictionary. The following are the known headers.
206     const std::string domain_;
207     const std::string path_;
208     const base::Time expiration_;  // Implied by max-age.
209     const std::set<int> ports_;
210
211     DISALLOW_COPY_AND_ASSIGN(Dictionary);
212   };
213
214   SdchManager();
215   ~SdchManager();
216
217   // Clear data (for browser data removal).
218   void ClearData();
219
220   // Record stats on various errors.
221   static void SdchErrorRecovery(ProblemCodes problem);
222
223   // Enables or disables SDCH compression.
224   static void EnableSdchSupport(bool enabled);
225
226   static bool sdch_enabled() { return g_sdch_enabled_; }
227
228   // Enables or disables SDCH compression over secure connection.
229   static void EnableSecureSchemeSupport(bool enabled);
230
231   static bool secure_scheme_supported() { return g_secure_scheme_supported_; }
232
233   // Briefly prevent further advertising of SDCH on this domain (if SDCH is
234   // enabled). After enough calls to IsInSupportedDomain() the blacklisting
235   // will be removed. Additional blacklists take exponentially more calls
236   // to IsInSupportedDomain() before the blacklisting is undone.
237   // Used when filter errors are found from a given domain, but it is plausible
238   // that the cause is temporary (such as application startup, where cached
239   // entries are used, but a dictionary is not yet loaded).
240   void BlacklistDomain(const GURL& url, ProblemCodes blacklist_reason);
241
242   // Used when SEVERE filter errors are found from a given domain, to prevent
243   // further use of SDCH on that domain.
244   void BlacklistDomainForever(const GURL& url, ProblemCodes blacklist_reason);
245
246   // Unit test only, this function resets enabling of sdch, and clears the
247   // blacklist.
248   void ClearBlacklistings();
249
250   // Unit test only, this function resets the blacklisting count for a domain.
251   void ClearDomainBlacklisting(const std::string& domain);
252
253   // Unit test only: indicate how many more times a domain will be blacklisted.
254   int BlackListDomainCount(const std::string& domain);
255
256   // Unit test only: Indicate what current blacklist increment is for a domain.
257   int BlacklistDomainExponential(const std::string& domain);
258
259   // Check to see if SDCH is enabled (globally), and the given URL is in a
260   // supported domain (i.e., not blacklisted, and either the specific supported
261   // domain, or all domains were assumed supported). If it is blacklist, reduce
262   // by 1 the number of times it will be reported as blacklisted.
263   bool IsInSupportedDomain(const GURL& url);
264
265   // Send out appropriate events notifying observers that a Get-Dictionary
266   // header has been seen.
267   void OnGetDictionary(const GURL& request_url, const GURL& dictionary_url);
268
269   // Find the vcdiff dictionary (the body of the sdch dictionary that appears
270   // after the meta-data headers like Domain:...) with the given |server_hash|
271   // to use to decompreses data that arrived as SDCH encoded content. Check to
272   // be sure the returned |dictionary| can be used for decoding content supplied
273   // in response to a request for |referring_url|.
274   // Return null in |dictionary| if there is no matching legal dictionary.
275   void GetVcdiffDictionary(const std::string& server_hash,
276                            const GURL& referring_url,
277                            scoped_refptr<Dictionary>* dictionary);
278
279   // Get list of available (pre-cached) dictionaries that we have already loaded
280   // into memory. The list is a comma separated list of (client) hashes per
281   // the SDCH spec.
282   void GetAvailDictionaryList(const GURL& target_url, std::string* list);
283
284   // Construct the pair of hashes for client and server to identify an SDCH
285   // dictionary. This is only made public to facilitate unit testing, but is
286   // otherwise private
287   static void GenerateHash(const std::string& dictionary_text,
288                            std::string* client_hash, std::string* server_hash);
289
290   // For Latency testing only, we need to know if we've succeeded in doing a
291   // round trip before starting our comparative tests. If ever we encounter
292   // problems with SDCH, we opt-out of the test unless/until we perform a
293   // complete SDCH decoding.
294   bool AllowLatencyExperiment(const GURL& url) const;
295
296   void SetAllowLatencyExperiment(const GURL& url, bool enable);
297
298   // Add an SDCH dictionary to our list of availible
299   // dictionaries. This addition will fail if addition is illegal
300   // (data in the dictionary is not acceptable from the
301   // dictionary_url; dictionary already added, etc.).
302   void AddSdchDictionary(const std::string& dictionary_text,
303                          const GURL& dictionary_url);
304
305   // Registration for events generated by the SDCH subsystem.
306   void AddObserver(SdchObserver* observer);
307   void RemoveObserver(SdchObserver* observer);
308
309  private:
310   struct BlacklistInfo {
311     BlacklistInfo()
312         : count(0),
313           exponential_count(0),
314           reason(MIN_PROBLEM_CODE) {}
315
316     int count;                   // # of times to refuse SDCH advertisement.
317     int exponential_count;       // Current exponential backoff ratchet.
318     ProblemCodes reason;         // Why domain was blacklisted.
319
320   };
321   typedef std::map<std::string, BlacklistInfo> DomainBlacklistInfo;
322   typedef std::set<std::string> ExperimentSet;
323
324   // Determines whether a "Get-Dictionary" header is legal (dictionary
325   // url has appropriate relationship to referrer url) in the SDCH
326   // protocol.  Return true if fetch is legal.
327   bool CanFetchDictionary(const GURL& referring_url,
328                           const GURL& dictionary_url) const;
329
330   // A map of dictionaries info indexed by the hash that the server provides.
331   typedef std::map<std::string, scoped_refptr<Dictionary> > DictionaryMap;
332
333   // Support SDCH compression, by advertising in headers.
334   static bool g_sdch_enabled_;
335
336   // Support SDCH compression for HTTPS requests and responses. When supported,
337   // HTTPS applicable dictionaries MUST have been acquired securely via HTTPS.
338   static bool g_secure_scheme_supported_;
339
340   // A simple implementation of a RFC 3548 "URL safe" base64 encoder.
341   static void UrlSafeBase64Encode(const std::string& input,
342                                   std::string* output);
343   DictionaryMap dictionaries_;
344
345   // List domains where decode failures have required disabling sdch.
346   DomainBlacklistInfo blacklisted_domains_;
347
348   // List of hostnames for which a latency experiment is allowed (because a
349   // round trip test has recently passed).
350   ExperimentSet allow_latency_experiment_;
351
352   // Observers that want to be notified of SDCH events.
353   // Assert list is empty on destruction since if there is an observer
354   // that hasn't removed itself from the list, that observer probably
355   // has a reference to the SdchManager.
356   ObserverList<SdchObserver, true> observers_;
357
358   base::ThreadChecker thread_checker_;
359
360   DISALLOW_COPY_AND_ASSIGN(SdchManager);
361 };
362
363 }  // namespace net
364
365 #endif  // NET_BASE_SDCH_MANAGER_H_