Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(314)

Side by Side Diff: Source/core/loader/DocumentThreadableLoader.cpp

Issue 1262593004: Prevent ThreadableLoaderClient methods from being called after failure notification (Closed) Base URL: https://chromium.googlesource.com/chromium/blink.git@master
Patch Set: Rebase Created 5 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « Source/core/loader/DocumentThreadableLoader.h ('k') | Source/core/loader/ThreadableLoader.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 /* 1 /*
2 * Copyright (C) 2011, 2012 Google Inc. All rights reserved. 2 * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
3 * Copyright (C) 2013, Intel Corporation 3 * Copyright (C) 2013, Intel Corporation
4 * 4 *
5 * Redistribution and use in source and binary forms, with or without 5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are 6 * modification, are permitted provided that the following conditions are
7 * met: 7 * met:
8 * 8 *
9 * * Redistributions of source code must retain the above copyright 9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer. 10 * notice, this list of conditions and the following disclaimer.
(...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after
138 , m_timeoutTimer(this, &DocumentThreadableLoader::didTimeout) 138 , m_timeoutTimer(this, &DocumentThreadableLoader::didTimeout)
139 , m_requestStartedSeconds(0.0) 139 , m_requestStartedSeconds(0.0)
140 , m_corsRedirectLimit(kMaxCORSRedirects) 140 , m_corsRedirectLimit(kMaxCORSRedirects)
141 , m_redirectMode(request.fetchRedirectMode()) 141 , m_redirectMode(request.fetchRedirectMode())
142 { 142 {
143 ASSERT(client); 143 ASSERT(client);
144 // Setting an outgoing referer is only supported in the async code path. 144 // Setting an outgoing referer is only supported in the async code path.
145 ASSERT(m_async || request.httpReferrer().isEmpty()); 145 ASSERT(m_async || request.httpReferrer().isEmpty());
146 146
147 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == DenyCrossO riginRequests) { 147 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == DenyCrossO riginRequests) {
148 m_client->didFail(ResourceError(errorDomainBlinkInternal, 0, request.url ().string(), "Cross origin requests are not supported.")); 148 ThreadableLoaderClient* client = m_client;
149 clear();
150 client->didFail(ResourceError(errorDomainBlinkInternal, 0, request.url() .string(), "Cross origin requests are not supported."));
151 // |this| may be dead here.
149 return; 152 return;
150 } 153 }
151 154
152 m_requestStartedSeconds = monotonicallyIncreasingTime(); 155 m_requestStartedSeconds = monotonicallyIncreasingTime();
153 156
154 // Save any CORS simple headers on the request here. If this request redirec ts cross-origin, we cancel the old request 157 // Save any CORS simple headers on the request here. If this request redirec ts cross-origin, we cancel the old request
155 // create a new one, and copy these headers. 158 // create a new one, and copy these headers.
156 const HTTPHeaderMap& headerMap = request.httpHeaderFields(); 159 const HTTPHeaderMap& headerMap = request.httpHeaderFields();
157 for (const auto& header : headerMap) { 160 for (const auto& header : headerMap) {
158 if (FetchUtils::isSimpleHeader(header.key, header.value)) 161 if (FetchUtils::isSimpleHeader(header.key, header.value))
(...skipping 20 matching lines...) Expand all
179 newRequest.setFetchRequestMode(WebURLRequest::FetchRequestModeCORS); 182 newRequest.setFetchRequestMode(WebURLRequest::FetchRequestModeCORS);
180 183
181 m_fallbackRequestForServiceWorker = adoptPtr(new ResourceRequest(request )); 184 m_fallbackRequestForServiceWorker = adoptPtr(new ResourceRequest(request ));
182 m_fallbackRequestForServiceWorker->setSkipServiceWorker(true); 185 m_fallbackRequestForServiceWorker->setSkipServiceWorker(true);
183 186
184 loadRequest(newRequest, m_resourceLoaderOptions); 187 loadRequest(newRequest, m_resourceLoaderOptions);
185 return; 188 return;
186 } 189 }
187 190
188 dispatchInitialRequest(request); 191 dispatchInitialRequest(request);
192 // |this| may be dead here in async mode.
189 } 193 }
190 194
191 void DocumentThreadableLoader::dispatchInitialRequest(const ResourceRequest& req uest) 195 void DocumentThreadableLoader::dispatchInitialRequest(const ResourceRequest& req uest)
192 { 196 {
193 if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossO riginRequests) { 197 if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossO riginRequests) {
194 loadRequest(request, m_resourceLoaderOptions); 198 loadRequest(request, m_resourceLoaderOptions);
195 return; 199 return;
196 } 200 }
197 201
198 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl); 202 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
199 203
200 makeCrossOriginAccessRequest(request); 204 makeCrossOriginAccessRequest(request);
205 // |this| may be dead here in async mode.
201 } 206 }
202 207
203 void DocumentThreadableLoader::makeCrossOriginAccessRequest(const ResourceReques t& request) 208 void DocumentThreadableLoader::makeCrossOriginAccessRequest(const ResourceReques t& request)
204 { 209 {
205 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl); 210 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
211 ASSERT(m_client);
212 ASSERT(!resource());
206 213
207 // Cross-origin requests are only allowed certain registered schemes. 214 // Cross-origin requests are only allowed certain registered schemes.
208 // We would catch this when checking response headers later, but there 215 // We would catch this when checking response headers later, but there
209 // is no reason to send a request, preflighted or not, that's guaranteed 216 // is no reason to send a request, preflighted or not, that's guaranteed
210 // to be denied. 217 // to be denied.
211 if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protoco l())) { 218 if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protoco l())) {
212 m_client->didFailAccessControlCheck(ResourceError(errorDomainBlinkIntern al, 0, request.url().string(), "Cross origin requests are only supported for pro tocol schemes: " + SchemeRegistry::listOfCORSEnabledURLSchemes() + ".")); 219 ThreadableLoaderClient* client = m_client;
220 clear();
221 client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal , 0, request.url().string(), "Cross origin requests are only supported for proto col schemes: " + SchemeRegistry::listOfCORSEnabledURLSchemes() + "."));
222 // |this| may be dead here in async mode.
213 return; 223 return;
214 } 224 }
215 225
216 // We use isSimpleOrForbiddenRequest() here since |request| may have been 226 // We use isSimpleOrForbiddenRequest() here since |request| may have been
217 // modified in the process of loading (not from the user's input). For 227 // modified in the process of loading (not from the user's input). For
218 // example, referrer. We need to accept them. For security, we must reject 228 // example, referrer. We need to accept them. For security, we must reject
219 // forbidden headers/methods at the point we accept user's input. Not here. 229 // forbidden headers/methods at the point we accept user's input. Not here.
220 if ((m_options.preflightPolicy == ConsiderPreflight && FetchUtils::isSimpleO rForbiddenRequest(request.httpMethod(), request.httpHeaderFields())) || m_option s.preflightPolicy == PreventPreflight) { 230 if ((m_options.preflightPolicy == ConsiderPreflight && FetchUtils::isSimpleO rForbiddenRequest(request.httpMethod(), request.httpHeaderFields())) || m_option s.preflightPolicy == PreventPreflight) {
221 ResourceRequest crossOriginRequest(request); 231 ResourceRequest crossOriginRequest(request);
222 ResourceLoaderOptions crossOriginOptions(m_resourceLoaderOptions); 232 ResourceLoaderOptions crossOriginOptions(m_resourceLoaderOptions);
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
266 double elapsedTime = monotonicallyIncreasingTime() - m_requestStartedSec onds; 276 double elapsedTime = monotonicallyIncreasingTime() - m_requestStartedSec onds;
267 double nextFire = timeoutMilliseconds / 1000.0; 277 double nextFire = timeoutMilliseconds / 1000.0;
268 double resolvedTime = std::max(nextFire - elapsedTime, 0.0); 278 double resolvedTime = std::max(nextFire - elapsedTime, 0.0);
269 m_timeoutTimer.startOneShot(resolvedTime, FROM_HERE); 279 m_timeoutTimer.startOneShot(resolvedTime, FROM_HERE);
270 } 280 }
271 } 281 }
272 282
273 void DocumentThreadableLoader::cancel() 283 void DocumentThreadableLoader::cancel()
274 { 284 {
275 cancelWithError(ResourceError()); 285 cancelWithError(ResourceError());
286 // |this| may be dead here.
276 } 287 }
277 288
278 void DocumentThreadableLoader::cancelWithError(const ResourceError& error) 289 void DocumentThreadableLoader::cancelWithError(const ResourceError& error)
279 { 290 {
280 RefPtr<DocumentThreadableLoader> protect(this); 291 // Cancel can re-enter and m_resource might be null here as a result.
292 if (!m_client || !resource()) {
293 clear();
294 return;
295 }
281 296
282 // Cancel can re-enter and m_resource might be null here as a result. 297 ResourceError errorForCallback = error;
283 if (m_client && resource()) { 298 if (errorForCallback.isNull()) {
284 ResourceError errorForCallback = error; 299 // FIXME: This error is sent to the client in didFail(), so it should no t be an internal one. Use FrameLoaderClient::cancelledError() instead.
285 if (errorForCallback.isNull()) { 300 errorForCallback = ResourceError(errorDomainBlinkInternal, 0, resource() ->url().string(), "Load cancelled");
286 // FIXME: This error is sent to the client in didFail(), so it shoul d not be an internal one. Use FrameLoaderClient::cancelledError() instead. 301 errorForCallback.setIsCancellation(true);
287 errorForCallback = ResourceError(errorDomainBlinkInternal, 0, resour ce()->url().string(), "Load cancelled");
288 errorForCallback.setIsCancellation(true);
289 }
290 m_client->didFail(errorForCallback);
291 } 302 }
292 clearResource(); 303
293 m_client = 0; 304 ThreadableLoaderClient* client = m_client;
294 m_requestStartedSeconds = 0.0; 305 clear();
306 client->didFail(errorForCallback);
307 // |this| may be dead here in async mode.
295 } 308 }
296 309
297 void DocumentThreadableLoader::setDefersLoading(bool value) 310 void DocumentThreadableLoader::setDefersLoading(bool value)
298 { 311 {
299 if (resource()) 312 if (resource())
300 resource()->setDefersLoading(value); 313 resource()->setDefersLoading(value);
301 } 314 }
302 315
316 void DocumentThreadableLoader::clear()
317 {
318 m_client = 0;
319
320 if (!m_async)
321 return;
322
323 clearResource();
324 m_timeoutTimer.stop();
325 m_requestStartedSeconds = 0.0;
326 }
327
303 // In this method, we can clear |request| to tell content::WebURLLoaderImpl of 328 // In this method, we can clear |request| to tell content::WebURLLoaderImpl of
304 // Chromium not to follow the redirect. This works only when this method is 329 // Chromium not to follow the redirect. This works only when this method is
305 // called by RawResource::willSendRequest(). If called by 330 // called by RawResource::willSendRequest(). If called by
306 // RawResource::didAddClient(), clearing |request| won't be propagated 331 // RawResource::didAddClient(), clearing |request| won't be propagated
307 // to content::WebURLLoaderImpl. So, this loader must also get detached from 332 // to content::WebURLLoaderImpl. So, this loader must also get detached from
308 // the resource by calling clearResource(). 333 // the resource by calling clearResource().
309 void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequ est& request, const ResourceResponse& redirectResponse) 334 void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequ est& request, const ResourceResponse& redirectResponse)
310 { 335 {
311 ASSERT(m_client); 336 ASSERT(m_client);
312 ASSERT_UNUSED(resource, resource == this->resource()); 337 ASSERT_UNUSED(resource, resource == this->resource());
313 ASSERT(m_async); 338 ASSERT(m_async);
314 339
315 RefPtr<DocumentThreadableLoader> protect(this);
316
317 if (m_actualRequest) { 340 if (m_actualRequest) {
318 reportResponseReceived(resource->identifier(), redirectResponse); 341 reportResponseReceived(resource->identifier(), redirectResponse);
319 342
320 clearResource(); 343 handlePreflightFailure(redirectResponse.url().string(), "Response for pr eflight is invalid (redirect)");
344 // |this| may be dead here.
345
321 request = ResourceRequest(); 346 request = ResourceRequest();
322 347
323 m_requestStartedSeconds = 0.0;
324
325 handlePreflightFailure(redirectResponse.url().string(), "Response for pr eflight is invalid (redirect)");
326
327 return; 348 return;
328 } 349 }
329 350
330 if (m_redirectMode == WebURLRequest::FetchRedirectModeManual) { 351 if (m_redirectMode == WebURLRequest::FetchRedirectModeManual) {
352 // Keep |this| alive even if the client release a reference in
353 // responseReceived().
354 RefPtr<DocumentThreadableLoader> protect(this);
355
331 // We use |m_redirectMode| to check the original redirect mode. 356 // We use |m_redirectMode| to check the original redirect mode.
332 // |request| is a new request for redirect. So we don't set the redirect 357 // |request| is a new request for redirect. So we don't set the redirect
333 // mode of it in WebURLLoaderImpl::Context::OnReceivedRedirect(). 358 // mode of it in WebURLLoaderImpl::Context::OnReceivedRedirect().
334 ASSERT(request.useStreamOnResponse()); 359 ASSERT(request.useStreamOnResponse());
335 // There is no need to read the body of redirect response because there 360 // There is no need to read the body of redirect response because there
336 // is no way to read the body of opaque-redirect filtered response's 361 // is no way to read the body of opaque-redirect filtered response's
337 // internal response. 362 // internal response.
338 // TODO(horo): If we support any API which expose the internal body, we 363 // TODO(horo): If we support any API which expose the internal body, we
339 // will have to read the body. And also HTTPCache changes will be needed 364 // will have to read the body. And also HTTPCache changes will be needed
340 // because it doesn't store the body of redirect responses. 365 // because it doesn't store the body of redirect responses.
341 responseReceived(resource, redirectResponse, adoptPtr(new EmptyDataHandl e())); 366 responseReceived(resource, redirectResponse, adoptPtr(new EmptyDataHandl e()));
342 notifyFinished(resource); 367
343 clearResource(); 368 if (m_client) {
369 ASSERT(!m_actualRequest);
370 notifyFinished(resource);
371 }
372
344 request = ResourceRequest(); 373 request = ResourceRequest();
374
345 return; 375 return;
346 } 376 }
347 377
348 if (m_redirectMode == WebURLRequest::FetchRedirectModeError || !isAllowedByC ontentSecurityPolicy(request.url(), ContentSecurityPolicy::DidRedirect)) { 378 if (m_redirectMode == WebURLRequest::FetchRedirectModeError || !isAllowedByC ontentSecurityPolicy(request.url(), ContentSecurityPolicy::DidRedirect)) {
349 m_client->didFailRedirectCheck(); 379 ThreadableLoaderClient* client = m_client;
380 clear();
381 client->didFailRedirectCheck();
382 // |this| may be dead here.
350 383
351 clearResource();
352 request = ResourceRequest(); 384 request = ResourceRequest();
353 385
354 m_requestStartedSeconds = 0.0;
355 return; 386 return;
356 } 387 }
357 388
358 // Allow same origin requests to continue after allowing clients to audit th e redirect. 389 // Allow same origin requests to continue after allowing clients to audit th e redirect.
359 if (isAllowedRedirect(request.url())) { 390 if (isAllowedRedirect(request.url())) {
360 if (m_client->isDocumentThreadableLoaderClient()) 391 if (m_client->isDocumentThreadableLoaderClient())
361 static_cast<DocumentThreadableLoaderClient*>(m_client)->willFollowRe direct(request, redirectResponse); 392 static_cast<DocumentThreadableLoaderClient*>(m_client)->willFollowRe direct(request, redirectResponse);
362 return; 393 return;
363 } 394 }
364 395
365 if (m_corsRedirectLimit <= 0) { 396 if (m_corsRedirectLimit <= 0) {
366 m_client->didFailRedirectCheck(); 397 ThreadableLoaderClient* client = m_client;
398 clear();
399 client->didFailRedirectCheck();
400 // |this| may be dead here.
367 } else if (m_options.crossOriginRequestPolicy == UseAccessControl) { 401 } else if (m_options.crossOriginRequestPolicy == UseAccessControl) {
368 --m_corsRedirectLimit; 402 --m_corsRedirectLimit;
369 403
370 InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document.fram e(), resource->identifier(), m_document.frame()->loader().documentLoader(), redi rectResponse, 0); 404 InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document.fram e(), resource->identifier(), m_document.frame()->loader().documentLoader(), redi rectResponse, 0);
371 405
372 bool allowRedirect = false; 406 bool allowRedirect = false;
373 String accessControlErrorDescription; 407 String accessControlErrorDescription;
374 408
375 // Non-simple cross origin requests (both preflight and actual one) are 409 // Non-simple cross origin requests (both preflight and actual one) are
376 // not allowed to follow redirect. 410 // not allowed to follow redirect.
(...skipping 27 matching lines...) Expand all
404 m_forceDoNotAllowStoredCredentials = true; 438 m_forceDoNotAllowStoredCredentials = true;
405 439
406 // Remove any headers that may have been added by the network layer that cause access control to fail. 440 // Remove any headers that may have been added by the network layer that cause access control to fail.
407 request.clearHTTPReferrer(); 441 request.clearHTTPReferrer();
408 request.clearHTTPOrigin(); 442 request.clearHTTPOrigin();
409 request.clearHTTPUserAgent(); 443 request.clearHTTPUserAgent();
410 // Add any CORS simple request headers which we previously saved fro m the original request. 444 // Add any CORS simple request headers which we previously saved fro m the original request.
411 for (const auto& header : m_simpleRequestHeaders) 445 for (const auto& header : m_simpleRequestHeaders)
412 request.setHTTPHeaderField(header.key, header.value); 446 request.setHTTPHeaderField(header.key, header.value);
413 makeCrossOriginAccessRequest(request); 447 makeCrossOriginAccessRequest(request);
448 // |this| may be dead here.
414 return; 449 return;
415 } 450 }
416 451
417 ResourceError error(errorDomainBlinkInternal, 0, redirectResponse.url(). string(), accessControlErrorDescription); 452 ThreadableLoaderClient* client = m_client;
418 m_client->didFailAccessControlCheck(error); 453 clear();
454 client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal , 0, redirectResponse.url().string(), accessControlErrorDescription));
455 // |this| may be dead here.
419 } else { 456 } else {
420 m_client->didFailRedirectCheck(); 457 ThreadableLoaderClient* client = m_client;
458 clear();
459 client->didFailRedirectCheck();
460 // |this| may be dead here.
421 } 461 }
422 462
423 clearResource();
424 request = ResourceRequest(); 463 request = ResourceRequest();
425
426 m_requestStartedSeconds = 0.0;
427 } 464 }
428 465
429 void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long b ytesSent, unsigned long long totalBytesToBeSent) 466 void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long b ytesSent, unsigned long long totalBytesToBeSent)
430 { 467 {
431 ASSERT(m_client); 468 ASSERT(m_client);
432 ASSERT_UNUSED(resource, resource == this->resource()); 469 ASSERT_UNUSED(resource, resource == this->resource());
433 ASSERT(m_async); 470 ASSERT(m_async);
434 471
435 m_client->didSendData(bytesSent, totalBytesToBeSent); 472 m_client->didSendData(bytesSent, totalBytesToBeSent);
473 // |this| may be dead here.
436 } 474 }
437 475
438 void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength ) 476 void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength )
439 { 477 {
440 ASSERT(m_client); 478 ASSERT(m_client);
441 ASSERT_UNUSED(resource, resource == this->resource()); 479 ASSERT_UNUSED(resource, resource == this->resource());
442 ASSERT(!m_actualRequest); 480 ASSERT(!m_actualRequest);
443 ASSERT(m_async); 481 ASSERT(m_async);
444 482
445 m_client->didDownloadData(dataLength); 483 m_client->didDownloadData(dataLength);
484 // |this| may be dead here.
446 } 485 }
447 486
448 void DocumentThreadableLoader::didReceiveResourceTiming(Resource* resource, cons t ResourceTimingInfo& info) 487 void DocumentThreadableLoader::didReceiveResourceTiming(Resource* resource, cons t ResourceTimingInfo& info)
449 { 488 {
450 ASSERT(m_client); 489 ASSERT(m_client);
451 ASSERT_UNUSED(resource, resource == this->resource()); 490 ASSERT_UNUSED(resource, resource == this->resource());
452 ASSERT(m_async); 491 ASSERT(m_async);
453 492
454 m_client->didReceiveResourceTiming(info); 493 m_client->didReceiveResourceTiming(info);
494 // |this| may be dead here.
455 } 495 }
456 496
457 void DocumentThreadableLoader::responseReceived(Resource* resource, const Resour ceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle) 497 void DocumentThreadableLoader::responseReceived(Resource* resource, const Resour ceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
458 { 498 {
459 ASSERT_UNUSED(resource, resource == this->resource()); 499 ASSERT_UNUSED(resource, resource == this->resource());
460 ASSERT(m_async); 500 ASSERT(m_async);
461 501
462 if (handle) 502 if (handle)
463 m_isUsingDataConsumerHandle = true; 503 m_isUsingDataConsumerHandle = true;
464 504
465 handleResponse(resource->identifier(), response, handle); 505 handleResponse(resource->identifier(), response, handle);
506 // |this| may be dead here.
466 } 507 }
467 508
468 void DocumentThreadableLoader::handlePreflightResponse(const ResourceResponse& r esponse) 509 void DocumentThreadableLoader::handlePreflightResponse(const ResourceResponse& r esponse)
469 { 510 {
470 String accessControlErrorDescription; 511 String accessControlErrorDescription;
471 512
472 if (!passesAccessControlCheck(response, effectiveAllowCredentials(), securit yOrigin(), accessControlErrorDescription, m_requestContext)) { 513 if (!passesAccessControlCheck(response, effectiveAllowCredentials(), securit yOrigin(), accessControlErrorDescription, m_requestContext)) {
473 handlePreflightFailure(response.url().string(), "Response to preflight r equest doesn't pass access control check: " + accessControlErrorDescription); 514 handlePreflightFailure(response.url().string(), "Response to preflight r equest doesn't pass access control check: " + accessControlErrorDescription);
515 // |this| may be dead here in async mode.
474 return; 516 return;
475 } 517 }
476 518
477 if (!passesPreflightStatusCheck(response, accessControlErrorDescription)) { 519 if (!passesPreflightStatusCheck(response, accessControlErrorDescription)) {
478 handlePreflightFailure(response.url().string(), accessControlErrorDescri ption); 520 handlePreflightFailure(response.url().string(), accessControlErrorDescri ption);
521 // |this| may be dead here in async mode.
479 return; 522 return;
480 } 523 }
481 524
482 OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new C rossOriginPreflightResultCacheItem(effectiveAllowCredentials())); 525 OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new C rossOriginPreflightResultCacheItem(effectiveAllowCredentials()));
483 if (!preflightResult->parse(response, accessControlErrorDescription) 526 if (!preflightResult->parse(response, accessControlErrorDescription)
484 || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod (), accessControlErrorDescription) 527 || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod (), accessControlErrorDescription)
485 || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeade rFields(), accessControlErrorDescription)) { 528 || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeade rFields(), accessControlErrorDescription)) {
486 handlePreflightFailure(response.url().string(), accessControlErrorDescri ption); 529 handlePreflightFailure(response.url().string(), accessControlErrorDescri ption);
530 // |this| may be dead here in async mode.
487 return; 531 return;
488 } 532 }
489 533
490 CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toSt ring(), m_actualRequest->url(), preflightResult.release()); 534 CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toSt ring(), m_actualRequest->url(), preflightResult.release());
491 } 535 }
492 536
493 void DocumentThreadableLoader::reportResponseReceived(unsigned long identifier, const ResourceResponse& response) 537 void DocumentThreadableLoader::reportResponseReceived(unsigned long identifier, const ResourceResponse& response)
494 { 538 {
495 DocumentLoader* loader = m_document.frame()->loader().documentLoader(); 539 DocumentLoader* loader = m_document.frame()->loader().documentLoader();
496 TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceReceiveResponse", TRACE_E VENT_SCOPE_THREAD, "data", InspectorReceiveResponseEvent::data(identifier, m_doc ument.frame(), response)); 540 TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceReceiveResponse", TRACE_E VENT_SCOPE_THREAD, "data", InspectorReceiveResponseEvent::data(identifier, m_doc ument.frame(), response));
497 LocalFrame* frame = m_document.frame(); 541 LocalFrame* frame = m_document.frame();
498 InspectorInstrumentation::didReceiveResourceResponse(frame, identifier, load er, response, resource() ? resource()->loader() : 0); 542 InspectorInstrumentation::didReceiveResourceResponse(frame, identifier, load er, response, resource() ? resource()->loader() : 0);
499 frame->console().reportResourceResponseReceived(loader, identifier, response ); 543 frame->console().reportResourceResponseReceived(loader, identifier, response );
500 } 544 }
501 545
502 void DocumentThreadableLoader::handleResponse(unsigned long identifier, const Re sourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle) 546 void DocumentThreadableLoader::handleResponse(unsigned long identifier, const Re sourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
503 { 547 {
504 ASSERT(m_client); 548 ASSERT(m_client);
505 549
506 if (m_actualRequest) { 550 if (m_actualRequest) {
507 reportResponseReceived(identifier, response); 551 reportResponseReceived(identifier, response);
508 handlePreflightResponse(response); 552 handlePreflightResponse(response);
553 // |this| may be dead here in async mode.
509 return; 554 return;
510 } 555 }
511 556
512 if (response.wasFetchedViaServiceWorker()) { 557 if (response.wasFetchedViaServiceWorker()) {
513 // It's still possible to reach here with null m_fallbackRequestForServi ceWorker 558 // It's still possible to reach here with null m_fallbackRequestForServi ceWorker
514 // if the request was for main resource loading (i.e. for SharedWorker), for which 559 // if the request was for main resource loading (i.e. for SharedWorker), for which
515 // we create DocumentLoader before the controller ServiceWorker is set. 560 // we create DocumentLoader before the controller ServiceWorker is set.
516 ASSERT(m_fallbackRequestForServiceWorker || m_requestContext == WebURLRe quest::RequestContextSharedWorker); 561 ASSERT(m_fallbackRequestForServiceWorker || m_requestContext == WebURLRe quest::RequestContextSharedWorker);
517 if (response.wasFallbackRequiredByServiceWorker()) { 562 if (response.wasFallbackRequiredByServiceWorker()) {
518 // At this point we must have m_fallbackRequestForServiceWorker. 563 // At this point we must have m_fallbackRequestForServiceWorker.
519 // (For SharedWorker the request won't be CORS or CORS-with-prefligh t, 564 // (For SharedWorker the request won't be CORS or CORS-with-prefligh t,
520 // therefore fallback-to-network is handled in the browser process 565 // therefore fallback-to-network is handled in the browser process
521 // when the ServiceWorker does not call respondWith().) 566 // when the ServiceWorker does not call respondWith().)
522 ASSERT(m_fallbackRequestForServiceWorker); 567 ASSERT(m_fallbackRequestForServiceWorker);
523 reportResponseReceived(identifier, response); 568 reportResponseReceived(identifier, response);
524 loadFallbackRequestForServiceWorker(); 569 loadFallbackRequestForServiceWorker();
570 // |this| may be dead here in async mode.
525 return; 571 return;
526 } 572 }
527 m_fallbackRequestForServiceWorker = nullptr; 573 m_fallbackRequestForServiceWorker = nullptr;
528 m_client->didReceiveResponse(identifier, response, handle); 574 m_client->didReceiveResponse(identifier, response, handle);
529 return; 575 return;
530 } 576 }
531 577
532 // Even if the request met the conditions to get handled by a Service Worker 578 // Even if the request met the conditions to get handled by a Service Worker
533 // in the constructor of this class (and therefore 579 // in the constructor of this class (and therefore
534 // |m_fallbackRequestForServiceWorker| is set), the Service Worker may skip 580 // |m_fallbackRequestForServiceWorker| is set), the Service Worker may skip
535 // processing the request. Only if the request is same origin, the skipped 581 // processing the request. Only if the request is same origin, the skipped
536 // response may come here (wasFetchedViaServiceWorker() returns false) since 582 // response may come here (wasFetchedViaServiceWorker() returns false) since
537 // such a request doesn't have to go through the CORS algorithm by calling 583 // such a request doesn't have to go through the CORS algorithm by calling
538 // loadFallbackRequestForServiceWorker(). 584 // loadFallbackRequestForServiceWorker().
539 // FIXME: We should use |m_sameOriginRequest| when we will support 585 // FIXME: We should use |m_sameOriginRequest| when we will support
540 // Suborigins (crbug.com/336894) for Service Worker. 586 // Suborigins (crbug.com/336894) for Service Worker.
541 ASSERT(!m_fallbackRequestForServiceWorker || securityOrigin()->canRequest(m_ fallbackRequestForServiceWorker->url())); 587 ASSERT(!m_fallbackRequestForServiceWorker || securityOrigin()->canRequest(m_ fallbackRequestForServiceWorker->url()));
542 m_fallbackRequestForServiceWorker = nullptr; 588 m_fallbackRequestForServiceWorker = nullptr;
543 589
544 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessC ontrol) { 590 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessC ontrol) {
545 String accessControlErrorDescription; 591 String accessControlErrorDescription;
546 if (!passesAccessControlCheck(response, effectiveAllowCredentials(), sec urityOrigin(), accessControlErrorDescription, m_requestContext)) { 592 if (!passesAccessControlCheck(response, effectiveAllowCredentials(), sec urityOrigin(), accessControlErrorDescription, m_requestContext)) {
547 reportResponseReceived(identifier, response); 593 reportResponseReceived(identifier, response);
548 m_client->didFailAccessControlCheck(ResourceError(errorDomainBlinkIn ternal, 0, response.url().string(), accessControlErrorDescription)); 594
595 ThreadableLoaderClient* client = m_client;
596 clear();
597 client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInte rnal, 0, response.url().string(), accessControlErrorDescription));
598 // |this| may be dead here.
549 return; 599 return;
550 } 600 }
551 } 601 }
552 602
553 m_client->didReceiveResponse(identifier, response, handle); 603 m_client->didReceiveResponse(identifier, response, handle);
554 } 604 }
555 605
556 void DocumentThreadableLoader::setSerializedCachedMetadata(Resource*, const char * data, size_t size) 606 void DocumentThreadableLoader::setSerializedCachedMetadata(Resource*, const char * data, size_t size)
557 { 607 {
558 if (m_actualRequest) 608 if (m_actualRequest)
559 return; 609 return;
560 m_client->didReceiveCachedMetadata(data, size); 610 m_client->didReceiveCachedMetadata(data, size);
611 // |this| may be dead here.
561 } 612 }
562 613
563 void DocumentThreadableLoader::dataReceived(Resource* resource, const char* data , unsigned dataLength) 614 void DocumentThreadableLoader::dataReceived(Resource* resource, const char* data , unsigned dataLength)
564 { 615 {
565 ASSERT_UNUSED(resource, resource == this->resource()); 616 ASSERT_UNUSED(resource, resource == this->resource());
566 ASSERT(m_async); 617 ASSERT(m_async);
567 618
568 if (m_isUsingDataConsumerHandle) 619 if (m_isUsingDataConsumerHandle)
569 return; 620 return;
570 621
571 handleReceivedData(data, dataLength); 622 handleReceivedData(data, dataLength);
623 // |this| may be dead here.
572 } 624 }
573 625
574 void DocumentThreadableLoader::handleReceivedData(const char* data, unsigned dat aLength) 626 void DocumentThreadableLoader::handleReceivedData(const char* data, unsigned dat aLength)
575 { 627 {
576 ASSERT(m_client); 628 ASSERT(m_client);
577 629
578 // Preflight data should be invisible to clients. 630 // Preflight data should be invisible to clients.
579 if (m_actualRequest) 631 if (m_actualRequest)
580 return; 632 return;
581 633
582 ASSERT(!m_fallbackRequestForServiceWorker); 634 ASSERT(!m_fallbackRequestForServiceWorker);
583 635
584 m_client->didReceiveData(data, dataLength); 636 m_client->didReceiveData(data, dataLength);
637 // |this| may be dead here in async mode.
585 } 638 }
586 639
587 void DocumentThreadableLoader::notifyFinished(Resource* resource) 640 void DocumentThreadableLoader::notifyFinished(Resource* resource)
588 { 641 {
589 ASSERT(m_client); 642 ASSERT(m_client);
590 ASSERT(resource == this->resource()); 643 ASSERT(resource == this->resource());
591 ASSERT(m_async); 644 ASSERT(m_async);
592 645
593 m_timeoutTimer.stop(); 646 if (resource->errorOccurred()) {
647 handleError(resource->resourceError());
648 // |this| may be dead here.
649 } else {
650 handleSuccessfulFinish(resource->identifier(), resource->loadFinishTime( ));
651 // |this| may be dead here.
652 }
653 }
594 654
595 if (resource->errorOccurred()) 655 void DocumentThreadableLoader::handleSuccessfulActualRequestFinish(unsigned long identifier, double finishTime)
596 m_client->didFail(resource->resourceError()); 656 {
597 else
598 handleSuccessfulFinish(resource->identifier(), resource->loadFinishTime( ));
599 } 657 }
600 658
601 void DocumentThreadableLoader::handleSuccessfulFinish(unsigned long identifier, double finishTime) 659 void DocumentThreadableLoader::handleSuccessfulFinish(unsigned long identifier, double finishTime)
602 { 660 {
603 ASSERT(!m_fallbackRequestForServiceWorker); 661 ASSERT(!m_fallbackRequestForServiceWorker);
604 662
605 if (m_actualRequest) { 663 if (!m_actualRequest) {
664 // FIXME: Timeout should be applied to whole fetch, not for each of
665 // preflight and actual request.
666 m_timeoutTimer.stop();
606 ASSERT(!m_sameOriginRequest); 667 ASSERT(!m_sameOriginRequest);
hiroshige 2015/09/17 08:39:33 This assertion is failing in many browser tests, e
tyoshino (SeeGerritForStatus) 2015/09/17 08:45:41 Sorry. I just forgot to fix the if-clause after re
607 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl); 668 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
608 loadActualRequest(); 669 loadActualRequest();
609 } else { 670 return;
610 // FIXME: Should prevent timeout from being overridden after finished lo ading, without
611 // resetting m_requestStartedSeconds to 0.0
612 m_client->didFinishLoading(identifier, finishTime);
613 } 671 }
672
673 ThreadableLoaderClient* client = m_client;
674 m_client = 0;
675 // Don't clear the resource as the client may need to access the downloaded
676 // file which will be released when the resource is destoryed.
677 if (m_async) {
678 m_timeoutTimer.stop();
679 m_requestStartedSeconds = 0.0;
680 }
681 client->didFinishLoading(identifier, finishTime);
682 // |this| may be dead here in async mode.
614 } 683 }
615 684
616 void DocumentThreadableLoader::didTimeout(Timer<DocumentThreadableLoader>* timer ) 685 void DocumentThreadableLoader::didTimeout(Timer<DocumentThreadableLoader>* timer )
617 { 686 {
618 ASSERT_UNUSED(timer, timer == &m_timeoutTimer); 687 ASSERT_UNUSED(timer, timer == &m_timeoutTimer);
619 688
620 // Using values from net/base/net_error_list.h ERR_TIMED_OUT, 689 // Using values from net/base/net_error_list.h ERR_TIMED_OUT,
621 // Same as existing FIXME above - this error should be coming from FrameLoad erClient to be identifiable. 690 // Same as existing FIXME above - this error should be coming from FrameLoad erClient to be identifiable.
622 static const int timeoutError = -7; 691 static const int timeoutError = -7;
623 ResourceError error("net", timeoutError, resource()->url(), String()); 692 ResourceError error("net", timeoutError, resource()->url(), String());
624 error.setIsTimeout(true); 693 error.setIsTimeout(true);
625 cancelWithError(error); 694 cancelWithError(error);
695 // |this| may be dead here.
626 } 696 }
627 697
628 void DocumentThreadableLoader::loadFallbackRequestForServiceWorker() 698 void DocumentThreadableLoader::loadFallbackRequestForServiceWorker()
629 { 699 {
630 clearResource(); 700 clearResource();
631 OwnPtr<ResourceRequest> fallbackRequest(m_fallbackRequestForServiceWorker.re lease()); 701 OwnPtr<ResourceRequest> fallbackRequest(m_fallbackRequestForServiceWorker.re lease());
632 dispatchInitialRequest(*fallbackRequest); 702 dispatchInitialRequest(*fallbackRequest);
703 // |this| may be dead here in async mode.
633 } 704 }
634 705
635 void DocumentThreadableLoader::loadActualRequest() 706 void DocumentThreadableLoader::loadActualRequest()
636 { 707 {
637 OwnPtr<ResourceRequest> actualRequest; 708 OwnPtr<ResourceRequest> actualRequest;
638 actualRequest.swap(m_actualRequest); 709 actualRequest.swap(m_actualRequest);
639 OwnPtr<ResourceLoaderOptions> actualOptions; 710 OwnPtr<ResourceLoaderOptions> actualOptions;
640 actualOptions.swap(m_actualOptions); 711 actualOptions.swap(m_actualOptions);
641 712
642 actualRequest->setHTTPOrigin(securityOrigin()->toAtomicString()); 713 actualRequest->setHTTPOrigin(securityOrigin()->toAtomicString());
643 714
644 clearResource(); 715 clearResource();
645 716
646 loadRequest(*actualRequest, *actualOptions); 717 loadRequest(*actualRequest, *actualOptions);
647 } 718 }
648 719
649 void DocumentThreadableLoader::handlePreflightFailure(const String& url, const S tring& errorDescription) 720 void DocumentThreadableLoader::handlePreflightFailure(const String& url, const S tring& errorDescription)
650 { 721 {
651 ResourceError error(errorDomainBlinkInternal, 0, url, errorDescription); 722 ResourceError error(errorDomainBlinkInternal, 0, url, errorDescription);
652 723
653 // Prevent handleSuccessfulFinish() from bypassing access check. 724 // Prevent handleSuccessfulFinish() from bypassing access check.
654 m_actualRequest = nullptr; 725 m_actualRequest = nullptr;
655 726
656 // FIXME: Should prevent timeout from being overridden after preflight failu re, without 727 ThreadableLoaderClient* client = m_client;
657 // resetting m_requestStartedSeconds to 0.0 728 clear();
658 m_client->didFailAccessControlCheck(error); 729 client->didFailAccessControlCheck(error);
730 // |this| may be dead here in async mode.
731 }
732
733 void DocumentThreadableLoader::handleError(const ResourceError& error)
734 {
735 // Copy the ResourceError instance to make it sure that the passed
736 // ResourceError is alive during didFail() even when the Resource is
737 // destructed during didFail().
738 ResourceError copiedError = error;
739
740 ThreadableLoaderClient* client = m_client;
741 clear();
742 client->didFail(copiedError);
743 // |this| may be dead here.
659 } 744 }
660 745
661 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, Resou rceLoaderOptions resourceLoaderOptions) 746 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, Resou rceLoaderOptions resourceLoaderOptions)
662 { 747 {
663 // Any credential should have been removed from the cross-site requests. 748 // Any credential should have been removed from the cross-site requests.
664 const KURL& requestURL = request.url(); 749 const KURL& requestURL = request.url();
665 ASSERT(m_sameOriginRequest || requestURL.user().isEmpty()); 750 ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
666 ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty()); 751 ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
667 752
668 // Update resourceLoaderOptions with enforced values. 753 // Update resourceLoaderOptions with enforced values.
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
716 // FIXME: A synchronous request does not tell us whether a redirect happened or not, so we guess by comparing the 801 // FIXME: A synchronous request does not tell us whether a redirect happened or not, so we guess by comparing the
717 // request and response URLs. This isn't a perfect test though, since a serv er can serve a redirect to the same URL that was 802 // request and response URLs. This isn't a perfect test though, since a serv er can serve a redirect to the same URL that was
718 // requested. Also comparing the request and response URLs as strings will f ail if the requestURL still has its credentials. 803 // requested. Also comparing the request and response URLs as strings will f ail if the requestURL still has its credentials.
719 if (requestURL != response.url() && (!isAllowedByContentSecurityPolicy(respo nse.url(), ContentSecurityPolicy::DidRedirect) || !isAllowedRedirect(response.ur l()))) { 804 if (requestURL != response.url() && (!isAllowedByContentSecurityPolicy(respo nse.url(), ContentSecurityPolicy::DidRedirect) || !isAllowedRedirect(response.ur l()))) {
720 m_client->didFailRedirectCheck(); 805 m_client->didFailRedirectCheck();
721 return; 806 return;
722 } 807 }
723 808
724 handleResponse(identifier, response, nullptr); 809 handleResponse(identifier, response, nullptr);
725 810
811 // handleResponse() may detect an error. In such a case (check |m_client|
812 // as it gets reset by clear() call), skip the rest.
813 //
814 // |this| is alive here since loadResourceSynchronously() keeps it alive
815 // until the end of the function.
816 if (!m_client)
817 return;
818
726 SharedBuffer* data = resource->resourceBuffer(); 819 SharedBuffer* data = resource->resourceBuffer();
727 if (data) 820 if (data)
728 handleReceivedData(data->data(), data->size()); 821 handleReceivedData(data->data(), data->size());
729 822
823 // The client may cancel this loader in handleReceivedData(). In such a
824 // case, skip the rest.
825 if (!m_client)
826 return;
827
730 handleSuccessfulFinish(identifier, 0.0); 828 handleSuccessfulFinish(identifier, 0.0);
731 } 829 }
732 830
733 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url) const 831 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url) const
734 { 832 {
735 if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) 833 if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
736 return true; 834 return true;
737 835
738 return m_sameOriginRequest && securityOrigin()->canRequest(url); 836 return m_sameOriginRequest && securityOrigin()->canRequest(url);
739 } 837 }
(...skipping 11 matching lines...) Expand all
751 return DoNotAllowStoredCredentials; 849 return DoNotAllowStoredCredentials;
752 return m_resourceLoaderOptions.allowCredentials; 850 return m_resourceLoaderOptions.allowCredentials;
753 } 851 }
754 852
755 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const 853 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
756 { 854 {
757 return m_securityOrigin ? m_securityOrigin.get() : m_document.securityOrigin (); 855 return m_securityOrigin ? m_securityOrigin.get() : m_document.securityOrigin ();
758 } 856 }
759 857
760 } // namespace blink 858 } // namespace blink
OLDNEW
« no previous file with comments | « Source/core/loader/DocumentThreadableLoader.h ('k') | Source/core/loader/ThreadableLoader.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698