yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 1 | // Copyright 2016 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 "content/browser/loader/mojo_async_resource_handler.h" |
| 6 | |
| 7 | #include <utility> |
| 8 | |
| 9 | #include "base/command_line.h" |
| 10 | #include "base/containers/hash_tables.h" |
| 11 | #include "base/logging.h" |
| 12 | #include "base/macros.h" |
| 13 | #include "base/strings/string_number_conversions.h" |
| 14 | #include "base/time/time.h" |
| 15 | #include "content/browser/loader/netlog_observer.h" |
| 16 | #include "content/browser/loader/resource_dispatcher_host_impl.h" |
| 17 | #include "content/browser/loader/resource_request_info_impl.h" |
| 18 | #include "content/common/resource_request_completion_status.h" |
yhirano | 5939370 | 2016-11-16 06:10:24 | [diff] [blame] | 19 | #include "content/public/browser/global_request_id.h" |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 20 | #include "content/public/browser/resource_dispatcher_host_delegate.h" |
| 21 | #include "content/public/common/resource_response.h" |
| 22 | #include "mojo/public/c/system/data_pipe.h" |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 23 | #include "mojo/public/cpp/bindings/message.h" |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 24 | #include "mojo/public/cpp/system/data_pipe.h" |
| 25 | #include "net/base/io_buffer.h" |
| 26 | #include "net/base/load_flags.h" |
| 27 | #include "net/base/mime_sniffer.h" |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 28 | #include "net/url_request/redirect_info.h" |
| 29 | |
| 30 | namespace content { |
| 31 | namespace { |
| 32 | |
| 33 | int g_allocation_size = MojoAsyncResourceHandler::kDefaultAllocationSize; |
| 34 | |
| 35 | // MimeTypeResourceHandler *implicitly* requires that the buffer size |
| 36 | // returned from OnWillRead should be larger than certain size. |
| 37 | // TODO(yhirano): Fix MimeTypeResourceHandler. |
| 38 | constexpr size_t kMinAllocationSize = 2 * net::kMaxBytesToSniff; |
| 39 | |
| 40 | constexpr size_t kMaxChunkSize = 32 * 1024; |
| 41 | |
| 42 | void GetNumericArg(const std::string& name, int* result) { |
| 43 | const std::string& value = |
| 44 | base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(name); |
| 45 | if (!value.empty()) |
| 46 | base::StringToInt(value, result); |
| 47 | } |
| 48 | |
| 49 | void InitializeResourceBufferConstants() { |
| 50 | static bool did_init = false; |
| 51 | if (did_init) |
| 52 | return; |
| 53 | did_init = true; |
| 54 | |
| 55 | GetNumericArg("resource-buffer-size", &g_allocation_size); |
| 56 | } |
| 57 | |
| 58 | } // namespace |
| 59 | |
| 60 | // This class is for sharing the ownership of a ScopedDataPipeProducerHandle |
| 61 | // between WriterIOBuffer and MojoAsyncResourceHandler. |
| 62 | class MojoAsyncResourceHandler::SharedWriter final |
| 63 | : public base::RefCountedThreadSafe<SharedWriter> { |
| 64 | public: |
| 65 | explicit SharedWriter(mojo::ScopedDataPipeProducerHandle writer) |
| 66 | : writer_(std::move(writer)) {} |
| 67 | mojo::DataPipeProducerHandle writer() { return writer_.get(); } |
| 68 | |
| 69 | private: |
| 70 | friend class base::RefCountedThreadSafe<SharedWriter>; |
| 71 | ~SharedWriter() {} |
| 72 | |
| 73 | const mojo::ScopedDataPipeProducerHandle writer_; |
| 74 | |
| 75 | DISALLOW_COPY_AND_ASSIGN(SharedWriter); |
| 76 | }; |
| 77 | |
| 78 | // This class is a IOBuffer subclass for data gotten from a |
| 79 | // ScopedDataPipeProducerHandle. |
| 80 | class MojoAsyncResourceHandler::WriterIOBuffer final |
| 81 | : public net::IOBufferWithSize { |
| 82 | public: |
| 83 | // |data| and |size| should be gotten from |writer| via BeginWriteDataRaw. |
| 84 | // They will be accesible via IOBuffer methods. As |writer| is stored in this |
| 85 | // instance, |data| will be kept valid as long as the following conditions |
| 86 | // hold: |
| 87 | // 1. |data| is not invalidated via EndWriteDataRaw. |
| 88 | // 2. |this| instance is alive. |
| 89 | WriterIOBuffer(scoped_refptr<SharedWriter> writer, void* data, size_t size) |
| 90 | : net::IOBufferWithSize(static_cast<char*>(data), size), |
| 91 | writer_(std::move(writer)) {} |
| 92 | |
| 93 | private: |
| 94 | ~WriterIOBuffer() override { |
| 95 | // Avoid deleting |data_| in the IOBuffer destructor. |
| 96 | data_ = nullptr; |
| 97 | } |
| 98 | |
| 99 | // This member is for keeping the writer alive. |
| 100 | scoped_refptr<SharedWriter> writer_; |
| 101 | |
| 102 | DISALLOW_COPY_AND_ASSIGN(WriterIOBuffer); |
| 103 | }; |
| 104 | |
| 105 | MojoAsyncResourceHandler::MojoAsyncResourceHandler( |
| 106 | net::URLRequest* request, |
| 107 | ResourceDispatcherHostImpl* rdh, |
yhirano | fe95d9b | 2016-11-07 04:17:47 | [diff] [blame] | 108 | mojom::URLLoaderAssociatedRequest mojo_request, |
| 109 | mojom::URLLoaderClientAssociatedPtr url_loader_client) |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 110 | : ResourceHandler(request), |
| 111 | rdh_(rdh), |
| 112 | binding_(this, std::move(mojo_request)), |
| 113 | url_loader_client_(std::move(url_loader_client)) { |
| 114 | DCHECK(url_loader_client_); |
| 115 | InitializeResourceBufferConstants(); |
yhirano | 5939370 | 2016-11-16 06:10:24 | [diff] [blame] | 116 | // This unretained pointer is safe, because |binding_| is owned by |this| and |
| 117 | // the callback will never be called after |this| is destroyed. |
| 118 | binding_.set_connection_error_handler( |
| 119 | base::Bind(&MojoAsyncResourceHandler::Cancel, base::Unretained(this))); |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 120 | } |
| 121 | |
| 122 | MojoAsyncResourceHandler::~MojoAsyncResourceHandler() { |
| 123 | if (has_checked_for_sufficient_resources_) |
| 124 | rdh_->FinishedWithResourcesForRequest(request()); |
| 125 | } |
| 126 | |
| 127 | bool MojoAsyncResourceHandler::OnRequestRedirected( |
| 128 | const net::RedirectInfo& redirect_info, |
| 129 | ResourceResponse* response, |
| 130 | bool* defer) { |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 131 | // Unlike OnResponseStarted, OnRequestRedirected will NOT be preceded by |
| 132 | // OnWillRead. |
| 133 | DCHECK(!shared_writer_); |
| 134 | |
| 135 | *defer = true; |
| 136 | request()->LogBlockedBy("MojoAsyncResourceHandler"); |
| 137 | did_defer_on_redirect_ = true; |
| 138 | |
| 139 | NetLogObserver::PopulateResponseInfo(request(), response); |
| 140 | response->head.encoded_data_length = request()->GetTotalReceivedBytes(); |
| 141 | response->head.request_start = request()->creation_time(); |
| 142 | response->head.response_start = base::TimeTicks::Now(); |
| 143 | // TODO(davidben): Is it necessary to pass the new first party URL for |
| 144 | // cookies? The only case where it can change is top-level navigation requests |
| 145 | // and hopefully those will eventually all be owned by the browser. It's |
| 146 | // possible this is still needed while renderer-owned ones exist. |
| 147 | url_loader_client_->OnReceiveRedirect(redirect_info, response->head); |
| 148 | return true; |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 149 | } |
| 150 | |
| 151 | bool MojoAsyncResourceHandler::OnResponseStarted(ResourceResponse* response, |
| 152 | bool* defer) { |
| 153 | const ResourceRequestInfoImpl* info = GetRequestInfo(); |
| 154 | |
| 155 | if (rdh_->delegate()) { |
| 156 | rdh_->delegate()->OnResponseStarted(request(), info->GetContext(), |
| 157 | response); |
| 158 | } |
| 159 | |
| 160 | NetLogObserver::PopulateResponseInfo(request(), response); |
| 161 | |
| 162 | response->head.request_start = request()->creation_time(); |
| 163 | response->head.response_start = base::TimeTicks::Now(); |
| 164 | sent_received_response_message_ = true; |
| 165 | url_loader_client_->OnReceiveResponse(response->head); |
| 166 | return true; |
| 167 | } |
| 168 | |
| 169 | bool MojoAsyncResourceHandler::OnWillStart(const GURL& url, bool* defer) { |
| 170 | return true; |
| 171 | } |
| 172 | |
| 173 | bool MojoAsyncResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf, |
| 174 | int* buf_size, |
| 175 | int min_size) { |
| 176 | DCHECK_EQ(-1, min_size); |
| 177 | |
| 178 | if (!CheckForSufficientResource()) |
| 179 | return false; |
| 180 | |
| 181 | if (!shared_writer_) { |
| 182 | MojoCreateDataPipeOptions options; |
| 183 | options.struct_size = sizeof(MojoCreateDataPipeOptions); |
| 184 | options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE; |
| 185 | options.element_num_bytes = 1; |
| 186 | options.capacity_num_bytes = g_allocation_size; |
| 187 | mojo::DataPipe data_pipe(options); |
| 188 | |
| 189 | url_loader_client_->OnStartLoadingResponseBody( |
| 190 | std::move(data_pipe.consumer_handle)); |
| 191 | if (!data_pipe.producer_handle.is_valid()) |
| 192 | return false; |
| 193 | |
| 194 | shared_writer_ = new SharedWriter(std::move(data_pipe.producer_handle)); |
| 195 | handle_watcher_.Start(shared_writer_->writer(), MOJO_HANDLE_SIGNAL_WRITABLE, |
| 196 | base::Bind(&MojoAsyncResourceHandler::OnWritable, |
| 197 | base::Unretained(this))); |
| 198 | |
| 199 | bool defer = false; |
| 200 | scoped_refptr<net::IOBufferWithSize> buffer; |
| 201 | if (!AllocateWriterIOBuffer(&buffer, &defer)) |
| 202 | return false; |
| 203 | if (!defer) { |
| 204 | if (static_cast<size_t>(buffer->size()) >= kMinAllocationSize) { |
| 205 | *buf = buffer_ = buffer; |
| 206 | *buf_size = buffer_->size(); |
| 207 | return true; |
| 208 | } |
| 209 | |
| 210 | // The allocated buffer is too small. |
| 211 | if (EndWrite(0) != MOJO_RESULT_OK) |
| 212 | return false; |
| 213 | } |
| 214 | DCHECK(!is_using_io_buffer_not_from_writer_); |
| 215 | is_using_io_buffer_not_from_writer_ = true; |
| 216 | buffer_ = new net::IOBufferWithSize(kMinAllocationSize); |
| 217 | } |
| 218 | |
| 219 | DCHECK_EQ(0u, buffer_offset_); |
| 220 | *buf = buffer_; |
| 221 | *buf_size = buffer_->size(); |
| 222 | return true; |
| 223 | } |
| 224 | |
| 225 | bool MojoAsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) { |
| 226 | DCHECK_GE(bytes_read, 0); |
| 227 | DCHECK(buffer_); |
| 228 | |
| 229 | if (!bytes_read) |
| 230 | return true; |
| 231 | |
| 232 | if (is_using_io_buffer_not_from_writer_) { |
| 233 | // Couldn't allocate a buffer on the data pipe in OnWillRead. |
| 234 | DCHECK_EQ(0u, buffer_bytes_read_); |
| 235 | buffer_bytes_read_ = bytes_read; |
| 236 | if (!CopyReadDataToDataPipe(defer)) |
| 237 | return false; |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 238 | if (*defer) { |
| 239 | request()->LogBlockedBy("MojoAsyncResourceHandler"); |
| 240 | did_defer_on_writing_ = true; |
| 241 | } |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 242 | return true; |
| 243 | } |
| 244 | |
| 245 | if (EndWrite(bytes_read) != MOJO_RESULT_OK) |
| 246 | return false; |
| 247 | // Allocate a buffer for the next OnWillRead call here, because OnWillRead |
| 248 | // doesn't have |defer| parameter. |
| 249 | if (!AllocateWriterIOBuffer(&buffer_, defer)) |
| 250 | return false; |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 251 | if (*defer) { |
| 252 | request()->LogBlockedBy("MojoAsyncResourceHandler"); |
| 253 | did_defer_on_writing_ = true; |
| 254 | } |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 255 | return true; |
| 256 | } |
| 257 | |
| 258 | void MojoAsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) { |
tzik | 6e20b74 | 2016-11-08 09:14:12 | [diff] [blame] | 259 | int64_t total_received_bytes = request()->GetTotalReceivedBytes(); |
| 260 | int64_t bytes_to_report = |
| 261 | total_received_bytes - reported_total_received_bytes_; |
| 262 | reported_total_received_bytes_ = total_received_bytes; |
| 263 | DCHECK_LE(0, bytes_to_report); |
| 264 | |
| 265 | url_loader_client_->OnDataDownloaded(bytes_downloaded, bytes_to_report); |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 266 | } |
| 267 | |
| 268 | void MojoAsyncResourceHandler::FollowRedirect() { |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 269 | if (!request()->status().is_success()) { |
| 270 | DVLOG(1) << "FollowRedirect for invalid request"; |
| 271 | return; |
| 272 | } |
| 273 | if (!did_defer_on_redirect_) { |
| 274 | DVLOG(1) << "Malformed FollowRedirect request"; |
| 275 | ReportBadMessage("Malformed FollowRedirect request"); |
| 276 | return; |
| 277 | } |
| 278 | |
| 279 | DCHECK(!did_defer_on_writing_); |
| 280 | did_defer_on_redirect_ = false; |
| 281 | request()->LogUnblocked(); |
| 282 | controller()->Resume(); |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 283 | } |
| 284 | |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 285 | void MojoAsyncResourceHandler::OnWritableForTesting() { |
| 286 | OnWritable(MOJO_RESULT_OK); |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 287 | } |
| 288 | |
| 289 | void MojoAsyncResourceHandler::SetAllocationSizeForTesting(size_t size) { |
| 290 | g_allocation_size = size; |
| 291 | } |
| 292 | |
| 293 | MojoResult MojoAsyncResourceHandler::BeginWrite(void** data, |
| 294 | uint32_t* available) { |
| 295 | MojoResult result = mojo::BeginWriteDataRaw( |
| 296 | shared_writer_->writer(), data, available, MOJO_WRITE_DATA_FLAG_NONE); |
| 297 | if (result == MOJO_RESULT_OK) |
| 298 | *available = std::min(*available, static_cast<uint32_t>(kMaxChunkSize)); |
| 299 | return result; |
| 300 | } |
| 301 | |
| 302 | MojoResult MojoAsyncResourceHandler::EndWrite(uint32_t written) { |
| 303 | return mojo::EndWriteDataRaw(shared_writer_->writer(), written); |
| 304 | } |
| 305 | |
| 306 | void MojoAsyncResourceHandler::OnResponseCompleted( |
| 307 | const net::URLRequestStatus& status, |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 308 | bool* defer) { |
| 309 | shared_writer_ = nullptr; |
| 310 | buffer_ = nullptr; |
| 311 | handle_watcher_.Cancel(); |
| 312 | |
| 313 | const ResourceRequestInfoImpl* info = GetRequestInfo(); |
| 314 | |
| 315 | // TODO(gavinp): Remove this CHECK when we figure out the cause of |
| 316 | // http://crbug.com/124680 . This check mirrors closely check in |
| 317 | // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore |
| 318 | // ResourceHandleInternal which asserts on its state and crashes. By crashing |
| 319 | // when the message is sent, we should get better crash reports. |
| 320 | CHECK(status.status() != net::URLRequestStatus::SUCCESS || |
| 321 | sent_received_response_message_); |
| 322 | |
| 323 | int error_code = status.error(); |
| 324 | bool was_ignored_by_handler = info->WasIgnoredByHandler(); |
| 325 | |
| 326 | DCHECK_NE(status.status(), net::URLRequestStatus::IO_PENDING); |
| 327 | // If this check fails, then we're in an inconsistent state because all |
| 328 | // requests ignored by the handler should be canceled (which should result in |
| 329 | // the ERR_ABORTED error code). |
| 330 | DCHECK(!was_ignored_by_handler || error_code == net::ERR_ABORTED); |
| 331 | |
| 332 | ResourceRequestCompletionStatus request_complete_data; |
| 333 | request_complete_data.error_code = error_code; |
| 334 | request_complete_data.was_ignored_by_handler = was_ignored_by_handler; |
| 335 | request_complete_data.exists_in_cache = request()->response_info().was_cached; |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 336 | request_complete_data.completion_time = base::TimeTicks::Now(); |
| 337 | request_complete_data.encoded_data_length = |
| 338 | request()->GetTotalReceivedBytes(); |
| 339 | |
| 340 | url_loader_client_->OnComplete(request_complete_data); |
| 341 | } |
| 342 | |
| 343 | bool MojoAsyncResourceHandler::CopyReadDataToDataPipe(bool* defer) { |
| 344 | while (true) { |
| 345 | scoped_refptr<net::IOBufferWithSize> dest; |
| 346 | if (!AllocateWriterIOBuffer(&dest, defer)) |
| 347 | return false; |
| 348 | if (*defer) |
| 349 | return true; |
| 350 | if (buffer_bytes_read_ == 0) { |
| 351 | // All bytes are copied. Save the buffer for the next OnWillRead call. |
| 352 | buffer_ = std::move(dest); |
| 353 | return true; |
| 354 | } |
| 355 | |
| 356 | size_t copied_size = |
| 357 | std::min(buffer_bytes_read_, static_cast<size_t>(dest->size())); |
| 358 | memcpy(dest->data(), buffer_->data() + buffer_offset_, copied_size); |
| 359 | buffer_offset_ += copied_size; |
| 360 | buffer_bytes_read_ -= copied_size; |
| 361 | if (EndWrite(copied_size) != MOJO_RESULT_OK) |
| 362 | return false; |
| 363 | |
| 364 | if (buffer_bytes_read_ == 0) { |
| 365 | // All bytes are copied. |
| 366 | buffer_offset_ = 0; |
| 367 | is_using_io_buffer_not_from_writer_ = false; |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | bool MojoAsyncResourceHandler::AllocateWriterIOBuffer( |
| 373 | scoped_refptr<net::IOBufferWithSize>* buf, |
| 374 | bool* defer) { |
| 375 | void* data = nullptr; |
| 376 | uint32_t available = 0; |
| 377 | MojoResult result = BeginWrite(&data, &available); |
| 378 | if (result == MOJO_RESULT_SHOULD_WAIT) { |
| 379 | *defer = true; |
| 380 | return true; |
| 381 | } |
| 382 | if (result != MOJO_RESULT_OK) |
| 383 | return false; |
| 384 | *buf = new WriterIOBuffer(shared_writer_, data, available); |
| 385 | return true; |
| 386 | } |
| 387 | |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 388 | bool MojoAsyncResourceHandler::CheckForSufficientResource() { |
| 389 | if (has_checked_for_sufficient_resources_) |
| 390 | return true; |
| 391 | has_checked_for_sufficient_resources_ = true; |
| 392 | |
| 393 | if (rdh_->HasSufficientResourcesForRequest(request())) |
| 394 | return true; |
| 395 | |
| 396 | controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES); |
| 397 | return false; |
| 398 | } |
| 399 | |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 400 | void MojoAsyncResourceHandler::OnWritable(MojoResult result) { |
| 401 | if (!did_defer_on_writing_) |
| 402 | return; |
| 403 | DCHECK(!did_defer_on_redirect_); |
| 404 | did_defer_on_writing_ = false; |
| 405 | |
| 406 | if (is_using_io_buffer_not_from_writer_) { |
| 407 | // |buffer_| is set to a net::IOBufferWithSize. Write the buffer contents |
| 408 | // to the data pipe. |
| 409 | DCHECK_GT(buffer_bytes_read_, 0u); |
| 410 | if (!CopyReadDataToDataPipe(&did_defer_on_writing_)) { |
| 411 | controller()->CancelWithError(net::ERR_FAILED); |
| 412 | return; |
| 413 | } |
| 414 | } else { |
| 415 | // Allocate a buffer for the next OnWillRead call here. |
| 416 | if (!AllocateWriterIOBuffer(&buffer_, &did_defer_on_writing_)) { |
| 417 | controller()->CancelWithError(net::ERR_FAILED); |
| 418 | return; |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | if (did_defer_on_writing_) { |
| 423 | // Continue waiting. |
| 424 | return; |
| 425 | } |
| 426 | request()->LogUnblocked(); |
| 427 | controller()->Resume(); |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 428 | } |
| 429 | |
yhirano | 5939370 | 2016-11-16 06:10:24 | [diff] [blame] | 430 | void MojoAsyncResourceHandler::Cancel() { |
| 431 | const ResourceRequestInfoImpl* info = GetRequestInfo(); |
| 432 | ResourceDispatcherHostImpl::Get()->CancelRequestFromRenderer( |
| 433 | GlobalRequestID(info->GetChildID(), info->GetRequestID())); |
| 434 | } |
| 435 | |
yhirano | 7153dc47 | 2016-11-16 09:42:46 | [diff] [blame^] | 436 | void MojoAsyncResourceHandler::ReportBadMessage(const std::string& error) { |
| 437 | mojo::ReportBadMessage(error); |
| 438 | } |
| 439 | |
yhirano | 72f6227 | 2016-08-13 12:50:06 | [diff] [blame] | 440 | } // namespace content |