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