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.
5 #include "net/filter/sdch_filter.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/values.h"
15 #include "net/base/sdch_manager.h"
16 #include "net/base/sdch_net_log_params.h"
17 #include "net/base/sdch_problem_codes.h"
18 #include "net/url_request/url_request_context.h"
20 #include "sdch/open-vcdiff/src/google/vcdecoder.h"
26 // Disambiguate various types of responses that trigger a meta-refresh,
27 // failure, or fallback to pass-through.
28 enum ResponseCorruptionDetectionCause
{
31 // 404 Http Response Code
34 // Not a 200 Http Response Code
37 // Cached before dictionary retrieved.
38 RESPONSE_OLD_UNENCODED
= 3,
40 // Speculative but incorrect SDCH filtering was added added.
41 RESPONSE_TENTATIVE_SDCH
= 4,
43 // Missing correct dict for decoding.
44 RESPONSE_NO_DICTIONARY
= 5,
46 // Not an SDCH response but should be.
47 RESPONSE_CORRUPT_SDCH
= 6,
49 // No dictionary was advertised with the request, the server claims
50 // to have encoded with SDCH anyway, but it isn't an SDCH response.
51 RESPONSE_ENCODING_LIE
= 7,
56 const char* ResponseCorruptionDetectionCauseToString(
57 ResponseCorruptionDetectionCause cause
) {
58 const char* cause_string
= "<unknown>";
61 cause_string
= "NONE";
66 case RESPONSE_NOT_200
:
67 cause_string
= "NOT_200";
69 case RESPONSE_OLD_UNENCODED
:
70 cause_string
= "OLD_UNENCODED";
72 case RESPONSE_TENTATIVE_SDCH
:
73 cause_string
= "TENTATIVE_SDCH";
75 case RESPONSE_NO_DICTIONARY
:
76 cause_string
= "NO_DICTIONARY";
78 case RESPONSE_CORRUPT_SDCH
:
79 cause_string
= "CORRUPT_SDCH";
81 case RESPONSE_ENCODING_LIE
:
82 cause_string
= "ENCODING_LIE";
85 cause_string
= "<Error: max enum value>";
91 base::Value
* NetLogSdchResponseCorruptionDetectionCallback(
92 ResponseCorruptionDetectionCause cause
,
94 NetLog::LogLevel log_level
) {
95 base::DictionaryValue
* dict
= new base::DictionaryValue();
96 dict
->SetString("cause", ResponseCorruptionDetectionCauseToString(cause
));
97 dict
->SetBoolean("cached", cached
);
103 SdchFilter::SdchFilter(FilterType type
, const FilterContext
& filter_context
)
105 filter_context_(filter_context
),
106 decoding_status_(DECODING_UNINITIALIZED
),
108 dictionary_hash_is_plausible_(false),
110 url_request_context_(filter_context
.GetURLRequestContext()),
111 dest_buffer_excess_(),
112 dest_buffer_excess_index_(0),
115 possible_pass_through_(false) {
116 bool success
= filter_context
.GetMimeType(&mime_type_
);
118 success
= filter_context
.GetURL(&url_
);
120 DCHECK(url_request_context_
->sdch_manager());
123 SdchFilter::~SdchFilter() {
124 // All code here is for gathering stats, and can be removed when SDCH is
125 // considered stable.
127 static int filter_use_count
= 0;
129 if (META_REFRESH_RECOVERY
== decoding_status_
) {
130 UMA_HISTOGRAM_COUNTS("Sdch3.FilterUseBeforeDisabling", filter_use_count
);
133 if (vcdiff_streaming_decoder_
.get()) {
134 if (!vcdiff_streaming_decoder_
->FinishDecoding()) {
135 decoding_status_
= DECODING_ERROR
;
136 LogSdchProblem(SDCH_INCOMPLETE_SDCH_CONTENT
);
137 // Make it possible for the user to hit reload, and get non-sdch content.
138 // Note this will "wear off" quickly enough, and is just meant to assure
139 // in some rare case that the user is not stuck.
140 url_request_context_
->sdch_manager()->BlacklistDomain(
141 url_
, SDCH_INCOMPLETE_SDCH_CONTENT
);
142 UMA_HISTOGRAM_COUNTS("Sdch3.PartialBytesIn",
143 static_cast<int>(filter_context_
.GetByteReadCount()));
144 UMA_HISTOGRAM_COUNTS("Sdch3.PartialVcdiffIn", source_bytes_
);
145 UMA_HISTOGRAM_COUNTS("Sdch3.PartialVcdiffOut", output_bytes_
);
149 if (!dest_buffer_excess_
.empty()) {
150 // Filter chaining error, or premature teardown.
151 LogSdchProblem(SDCH_UNFLUSHED_CONTENT
);
152 UMA_HISTOGRAM_COUNTS("Sdch3.UnflushedBytesIn",
153 static_cast<int>(filter_context_
.GetByteReadCount()));
154 UMA_HISTOGRAM_COUNTS("Sdch3.UnflushedBufferSize",
155 dest_buffer_excess_
.size());
156 UMA_HISTOGRAM_COUNTS("Sdch3.UnflushedVcdiffIn", source_bytes_
);
157 UMA_HISTOGRAM_COUNTS("Sdch3.UnflushedVcdiffOut", output_bytes_
);
160 if (filter_context_
.IsCachedContent()) {
161 // Not a real error, but it is useful to have this tally.
162 // TODO(jar): Remove this stat after SDCH stability is validated.
163 LogSdchProblem(SDCH_CACHE_DECODED
);
164 return; // We don't need timing stats, and we aready got ratios.
167 switch (decoding_status_
) {
168 case DECODING_IN_PROGRESS
: {
170 UMA_HISTOGRAM_PERCENTAGE("Sdch3.Network_Decode_Ratio_a",
172 (filter_context_
.GetByteReadCount() * 100) / output_bytes_
));
173 UMA_HISTOGRAM_COUNTS("Sdch3.Network_Decode_Bytes_VcdiffOut_a",
175 filter_context_
.RecordPacketStats(FilterContext::SDCH_DECODE
);
177 // Allow latency experiments to proceed.
178 url_request_context_
->sdch_manager()->SetAllowLatencyExperiment(
183 filter_context_
.RecordPacketStats(FilterContext::SDCH_PASSTHROUGH
);
186 case DECODING_UNINITIALIZED
: {
187 LogSdchProblem(SDCH_UNINITIALIZED
);
190 case WAITING_FOR_DICTIONARY_SELECTION
: {
191 LogSdchProblem(SDCH_PRIOR_TO_DICTIONARY
);
194 case DECODING_ERROR
: {
195 LogSdchProblem(SDCH_DECODE_ERROR
);
198 case META_REFRESH_RECOVERY
: {
199 // Already accounted for when set.
205 bool SdchFilter::InitDecoding(Filter::FilterType filter_type
) {
206 if (decoding_status_
!= DECODING_UNINITIALIZED
)
209 // Handle case where sdch filter is guessed, but not required.
210 if (FILTER_TYPE_SDCH_POSSIBLE
== filter_type
)
211 possible_pass_through_
= true;
213 // Initialize decoder only after we have a dictionary in hand.
214 decoding_status_
= WAITING_FOR_DICTIONARY_SELECTION
;
219 static const char* kDecompressionErrorHtml
=
220 "<head><META HTTP-EQUIV=\"Refresh\" CONTENT=\"0\"></head>"
221 "<div style=\"position:fixed;top:0;left:0;width:100%;border-width:thin;"
222 "border-color:black;border-style:solid;text-align:left;font-family:arial;"
223 "font-size:10pt;foreground-color:black;background-color:white\">"
224 "An error occurred. This page will be reloaded shortly. "
225 "Or press the \"reload\" button now to reload it immediately."
228 static const char* kDecompressionErrorHtml
=
229 "<head><META HTTP-EQUIV=\"Refresh\" CONTENT=\"0\"></head>";
232 Filter::FilterStatus
SdchFilter::ReadFilteredData(char* dest_buffer
,
234 int available_space
= *dest_len
;
235 *dest_len
= 0; // Nothing output yet.
237 if (!dest_buffer
|| available_space
<= 0)
240 if (WAITING_FOR_DICTIONARY_SELECTION
== decoding_status_
) {
241 FilterStatus status
= InitializeDictionary();
242 if (FILTER_NEED_MORE_DATA
== status
)
243 return FILTER_NEED_MORE_DATA
;
244 if (FILTER_ERROR
== status
) {
245 DCHECK_EQ(DECODING_ERROR
, decoding_status_
);
246 DCHECK_EQ(0u, dest_buffer_excess_index_
);
247 DCHECK(dest_buffer_excess_
.empty());
248 // This is where we try very hard to do error recovery, and make this
249 // protocol robust in the face of proxies that do many different things.
250 // If we decide that things are looking very bad (too hard to recover),
251 // we may even issue a "meta-refresh" to reload the page without an SDCH
252 // advertisement (so that we are sure we're not hurting anything).
254 // Watch out for an error page inserted by the proxy as part of a 40x
255 // error response. When we see such content molestation, we certainly
256 // need to fall into the meta-refresh case.
257 ResponseCorruptionDetectionCause cause
= RESPONSE_NONE
;
258 if (filter_context_
.GetResponseCode() == 404) {
259 // We could be more generous, but for now, only a "NOT FOUND" code will
260 // cause a pass through. All other bad codes will fall into a
262 LogSdchProblem(SDCH_PASS_THROUGH_404_CODE
);
263 cause
= RESPONSE_404
;
264 decoding_status_
= PASS_THROUGH
;
265 } else if (filter_context_
.GetResponseCode() != 200) {
266 // We need to meta-refresh, with SDCH disabled.
267 cause
= RESPONSE_NOT_200
;
268 } else if (filter_context_
.IsCachedContent()
269 && !dictionary_hash_is_plausible_
) {
270 // We must have hit the back button, and gotten content that was fetched
271 // before we *really* advertised SDCH and a dictionary.
272 LogSdchProblem(SDCH_PASS_THROUGH_OLD_CACHED
);
273 decoding_status_
= PASS_THROUGH
;
274 cause
= RESPONSE_OLD_UNENCODED
;
275 } else if (possible_pass_through_
) {
276 // This is the potentially most graceful response. There really was no
277 // error. We were just overly cautious when we added a TENTATIVE_SDCH.
278 // We added the sdch coding tag, and it should not have been added.
279 // This can happen in server experiments, where the server decides
280 // not to use sdch, even though there is a dictionary. To be
281 // conservative, we locally added the tentative sdch (fearing that a
282 // proxy stripped it!) and we must now recant (pass through).
284 // However.... just to be sure we don't get burned by proxies that
285 // re-compress with gzip or other system, we can sniff to see if this
286 // is compressed data etc. For now, we do nothing, which gets us into
287 // the meta-refresh result.
288 // TODO(jar): Improve robustness by sniffing for valid text that we can
289 // actual use re: decoding_status_ = PASS_THROUGH;
290 cause
= RESPONSE_TENTATIVE_SDCH
;
291 } else if (dictionary_hash_is_plausible_
) {
292 // We need a meta-refresh since we don't have the dictionary.
293 // The common cause is a restart of the browser, where we try to render
294 // cached content that was saved when we had a dictionary.
295 cause
= RESPONSE_NO_DICTIONARY
;
296 } else if (filter_context_
.SdchDictionariesAdvertised()) {
297 // This is a very corrupt SDCH request response. We can't decode it.
298 // We'll use a meta-refresh, and get content without asking for SDCH.
299 // This will also progressively disable SDCH for this domain.
300 cause
= RESPONSE_CORRUPT_SDCH
;
302 // One of the first 9 bytes precluded consideration as a hash.
303 // This can't be an SDCH payload, even though the server said it was.
304 // This is a major error, as the server or proxy tagged this SDCH even
306 // Meta-refresh won't help, as we didn't advertise an SDCH dictionary!!
307 // Worse yet, meta-refresh could lead to an infinite refresh loop.
308 LogSdchProblem(SDCH_PASSING_THROUGH_NON_SDCH
);
309 decoding_status_
= PASS_THROUGH
;
310 // ... but further back-off on advertising SDCH support.
311 url_request_context_
->sdch_manager()->BlacklistDomain(
312 url_
, SDCH_PASSING_THROUGH_NON_SDCH
);
313 cause
= RESPONSE_ENCODING_LIE
;
315 DCHECK_NE(RESPONSE_NONE
, cause
);
317 // Use if statement rather than ?: because UMA_HISTOGRAM_ENUMERATION
318 // caches the histogram name based on the call site.
319 if (filter_context_
.IsCachedContent()) {
320 UMA_HISTOGRAM_ENUMERATION(
321 "Sdch3.ResponseCorruptionDetection.Cached", cause
, RESPONSE_MAX
);
323 UMA_HISTOGRAM_ENUMERATION(
324 "Sdch3.ResponseCorruptionDetection.Uncached", cause
, RESPONSE_MAX
);
326 filter_context_
.GetNetLog().AddEvent(
327 NetLog::TYPE_SDCH_RESPONSE_CORRUPTION_DETECTION
,
328 base::Bind(&NetLogSdchResponseCorruptionDetectionCallback
, cause
,
329 filter_context_
.IsCachedContent()));
331 if (decoding_status_
== PASS_THROUGH
) {
332 dest_buffer_excess_
= dictionary_hash_
; // Send what we scanned.
334 // This is where we try to do the expensive meta-refresh.
335 if (std::string::npos
== mime_type_
.find("text/html")) {
336 // Since we can't do a meta-refresh (along with an exponential
337 // backoff), we'll just make sure this NEVER happens again.
338 SdchProblemCode problem
= (filter_context_
.IsCachedContent()
339 ? SDCH_CACHED_META_REFRESH_UNSUPPORTED
340 : SDCH_META_REFRESH_UNSUPPORTED
);
341 url_request_context_
->sdch_manager()->BlacklistDomainForever(
343 LogSdchProblem(problem
);
346 // HTML content means we can issue a meta-refresh, and get the content
347 // again, perhaps without SDCH (to be safe).
348 if (filter_context_
.IsCachedContent()) {
349 // Cached content is probably a startup tab, so we'll just get fresh
350 // content and try again, without disabling sdch.
351 LogSdchProblem(SDCH_META_REFRESH_CACHED_RECOVERY
);
353 // Since it wasn't in the cache, we definately need at least some
354 // period of blacklisting to get the correct content.
355 url_request_context_
->sdch_manager()->BlacklistDomain(
356 url_
, SDCH_META_REFRESH_RECOVERY
);
357 LogSdchProblem(SDCH_META_REFRESH_RECOVERY
);
359 decoding_status_
= META_REFRESH_RECOVERY
;
360 // Issue a meta redirect with SDCH disabled.
361 dest_buffer_excess_
= kDecompressionErrorHtml
;
364 DCHECK_EQ(DECODING_IN_PROGRESS
, decoding_status_
);
368 int amount
= OutputBufferExcess(dest_buffer
, available_space
);
370 dest_buffer
+= amount
;
371 available_space
-= amount
;
372 DCHECK_GE(available_space
, 0);
374 if (available_space
<= 0)
376 DCHECK(dest_buffer_excess_
.empty());
377 DCHECK_EQ(0u, dest_buffer_excess_index_
);
379 if (decoding_status_
!= DECODING_IN_PROGRESS
) {
380 if (META_REFRESH_RECOVERY
== decoding_status_
) {
381 // Absorb all input data. We've already output page reload HTML.
382 next_stream_data_
= NULL
;
383 stream_data_len_
= 0;
384 return FILTER_NEED_MORE_DATA
;
386 if (PASS_THROUGH
== decoding_status_
) {
387 // We must pass in available_space, but it will be changed to bytes_used.
388 FilterStatus result
= CopyOut(dest_buffer
, &available_space
);
389 // Accumulate the returned count of bytes_used (a.k.a., available_space).
390 *dest_len
+= available_space
;
394 decoding_status_
= DECODING_ERROR
;
398 if (!next_stream_data_
|| stream_data_len_
<= 0)
399 return FILTER_NEED_MORE_DATA
;
401 bool ret
= vcdiff_streaming_decoder_
->DecodeChunk(
402 next_stream_data_
, stream_data_len_
, &dest_buffer_excess_
);
403 // Assume all data was used in decoding.
404 next_stream_data_
= NULL
;
405 source_bytes_
+= stream_data_len_
;
406 stream_data_len_
= 0;
407 output_bytes_
+= dest_buffer_excess_
.size();
409 vcdiff_streaming_decoder_
.reset(NULL
); // Don't call it again.
410 decoding_status_
= DECODING_ERROR
;
411 LogSdchProblem(SDCH_DECODE_BODY_ERROR
);
415 amount
= OutputBufferExcess(dest_buffer
, available_space
);
417 dest_buffer
+= amount
;
418 available_space
-= amount
;
419 if (0 == available_space
&& !dest_buffer_excess_
.empty())
421 return FILTER_NEED_MORE_DATA
;
424 Filter::FilterStatus
SdchFilter::InitializeDictionary() {
425 const size_t kServerIdLength
= 9; // Dictionary hash plus null from server.
426 size_t bytes_needed
= kServerIdLength
- dictionary_hash_
.size();
427 DCHECK_GT(bytes_needed
, 0u);
428 if (!next_stream_data_
)
429 return FILTER_NEED_MORE_DATA
;
430 if (static_cast<size_t>(stream_data_len_
) < bytes_needed
) {
431 dictionary_hash_
.append(next_stream_data_
, stream_data_len_
);
432 next_stream_data_
= NULL
;
433 stream_data_len_
= 0;
434 return FILTER_NEED_MORE_DATA
;
436 dictionary_hash_
.append(next_stream_data_
, bytes_needed
);
437 DCHECK(kServerIdLength
== dictionary_hash_
.size());
438 stream_data_len_
-= bytes_needed
;
439 DCHECK_LE(0, stream_data_len_
);
440 if (stream_data_len_
> 0)
441 next_stream_data_
+= bytes_needed
;
443 next_stream_data_
= NULL
;
445 DCHECK(!dictionary_
);
446 dictionary_hash_is_plausible_
= true; // Assume plausible, but check.
448 SdchProblemCode rv
= SDCH_OK
;
449 if ('\0' == dictionary_hash_
[kServerIdLength
- 1]) {
450 std::string
server_hash(dictionary_hash_
, 0, kServerIdLength
- 1);
451 SdchManager::DictionarySet
* handle
=
452 filter_context_
.SdchDictionariesAdvertised();
454 dictionary_
= handle
->GetDictionary(server_hash
);
456 // This is a hack. Naively, the dictionaries available for
457 // decoding should be only the ones advertised. However, there are
458 // cases, specifically resources encoded with old dictionaries living
459 // in the cache, that mean the full set of dictionaries should be made
460 // available for decoding. It's not known how often this happens;
461 // if it happens rarely enough, this code can be removed.
463 // TODO(rdsmith): Long-term, a better solution is necessary, since
464 // an entry in the cache being encoded with the dictionary doesn't
465 // guarantee that the dictionary is present. That solution probably
466 // involves storing unencoded resources in the cache, but might
467 // involve evicting encoded resources on dictionary removal.
468 // See http://crbug.com/383405.
469 unexpected_dictionary_handle_
=
470 url_request_context_
->sdch_manager()->GetDictionarySetByHash(
471 url_
, server_hash
, &rv
);
472 if (unexpected_dictionary_handle_
) {
473 dictionary_
= unexpected_dictionary_handle_
->GetDictionary(server_hash
);
474 // Override SDCH_OK rv; this is still worth logging.
475 rv
= (filter_context_
.IsCachedContent() ?
476 SDCH_UNADVERTISED_DICTIONARY_USED_CACHED
:
477 SDCH_UNADVERTISED_DICTIONARY_USED
);
479 // Since dictionary was not found, check to see if hash was
481 DCHECK(dictionary_hash_
.size() == kServerIdLength
);
482 rv
= SDCH_DICTIONARY_HASH_NOT_FOUND
;
483 for (size_t i
= 0; i
< kServerIdLength
- 1; ++i
) {
484 char base64_char
= dictionary_hash_
[i
];
485 if (!isalnum(base64_char
) &&
486 '-' != base64_char
&& '_' != base64_char
) {
487 dictionary_hash_is_plausible_
= false;
488 rv
= SDCH_DICTIONARY_HASH_MALFORMED
;
495 dictionary_hash_is_plausible_
= false;
496 rv
= SDCH_DICTIONARY_HASH_MALFORMED
;
503 decoding_status_
= DECODING_ERROR
;
507 vcdiff_streaming_decoder_
.reset(new open_vcdiff::VCDiffStreamingDecoder
);
508 vcdiff_streaming_decoder_
->SetAllowVcdTarget(false);
509 vcdiff_streaming_decoder_
->StartDecoding(dictionary_
->text().data(),
510 dictionary_
->text().size());
511 decoding_status_
= DECODING_IN_PROGRESS
;
515 int SdchFilter::OutputBufferExcess(char* const dest_buffer
,
516 size_t available_space
) {
517 if (dest_buffer_excess_
.empty())
519 DCHECK(dest_buffer_excess_
.size() > dest_buffer_excess_index_
);
520 size_t amount
= std::min(available_space
,
521 dest_buffer_excess_
.size() - dest_buffer_excess_index_
);
522 memcpy(dest_buffer
, dest_buffer_excess_
.data() + dest_buffer_excess_index_
,
524 dest_buffer_excess_index_
+= amount
;
525 if (dest_buffer_excess_
.size() <= dest_buffer_excess_index_
) {
526 DCHECK(dest_buffer_excess_
.size() == dest_buffer_excess_index_
);
527 dest_buffer_excess_
.clear();
528 dest_buffer_excess_index_
= 0;
533 void SdchFilter::LogSdchProblem(SdchProblemCode problem
) {
534 SdchManager::SdchErrorRecovery(problem
);
535 filter_context_
.GetNetLog().AddEvent(
536 NetLog::TYPE_SDCH_DECODING_ERROR
,
537 base::Bind(&NetLogSdchResourceProblemCallback
, problem
));