Use asynchronous ResourceHandleClient calls for WebKit1
authorachristensen@apple.com <achristensen@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 1 Nov 2017 01:13:04 +0000 (01:13 +0000)
committerachristensen@apple.com <achristensen@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 1 Nov 2017 01:13:04 +0000 (01:13 +0000)
https://bugs.webkit.org/show_bug.cgi?id=160677

Reviewed by Brady Eidson.

Source/WebCore:

Covered by existing tests.

* PlatformAppleWin.cmake:
* PlatformMac.cmake:
* WebCore.xcodeproj/project.pbxproj:
* loader/ResourceLoader.cpp:
(WebCore::ResourceLoader::willSendRequestAsync):
(WebCore::ResourceLoader::didReceiveResponseAsync):
(WebCore::ResourceLoader::canAuthenticateAgainstProtectionSpaceAsync):
* loader/ResourceLoader.h:
* loader/appcache/ApplicationCacheGroup.cpp:
(WebCore::ApplicationCacheGroup::didReceiveResponseAsync):
(WebCore::ApplicationCacheGroup::willSendRequestAsync):
(WebCore::ApplicationCacheGroup::canAuthenticateAgainstProtectionSpaceAsync):
(WebCore::ApplicationCacheGroup::didReceiveResponse): Deleted.
* loader/appcache/ApplicationCacheGroup.h:
* platform/network/BlobResourceHandle.cpp:
(WebCore::BlobResourceHandle::continueDidReceiveResponse):
(WebCore::BlobResourceHandle::getSizeForNext):
(WebCore::BlobResourceHandle::notifyResponseOnSuccess):
(WebCore::BlobResourceHandle::notifyResponseOnError):
* platform/network/PingHandle.h:
* platform/network/ResourceHandle.cpp:
(WebCore::ResourceHandle::didReceiveResponse):
(WebCore::ResourceHandle::usesAsyncCallbacks): Deleted.
* platform/network/ResourceHandle.h:
* platform/network/ResourceHandleClient.cpp:
(WebCore::ResourceHandleClient::~ResourceHandleClient):
(WebCore::ResourceHandleClient::willSendRequest): Deleted.
(WebCore::ResourceHandleClient::willSendRequestAsync): Deleted.
(WebCore::ResourceHandleClient::didReceiveResponseAsync): Deleted.
(WebCore::ResourceHandleClient::canAuthenticateAgainstProtectionSpaceAsync): Deleted.
* platform/network/ResourceHandleClient.h:
(WebCore::ResourceHandleClient::didReceiveAuthenticationChallenge):
(WebCore::ResourceHandleClient::didReceiveResponse): Deleted.
(WebCore::ResourceHandleClient::usesAsyncCallbacks): Deleted.
(WebCore::ResourceHandleClient::canAuthenticateAgainstProtectionSpace): Deleted.
* platform/network/ResourceHandleInternal.h:
(WebCore::ResourceHandleInternal::ResourceHandleInternal):
* platform/network/SynchronousLoaderClient.cpp:
(WebCore::SynchronousLoaderClient::willSendRequestAsync):
(WebCore::SynchronousLoaderClient::canAuthenticateAgainstProtectionSpaceAsync):
(WebCore::SynchronousLoaderClient::didReceiveResponseAsync):
(WebCore::SynchronousLoaderClient::didFinishLoading):
(WebCore::SynchronousLoaderClient::didFail):
(WebCore::SynchronousLoaderClient::willSendRequest): Deleted.
(WebCore::SynchronousLoaderClient::canAuthenticateAgainstProtectionSpace): Deleted.
(WebCore::SynchronousLoaderClient::didReceiveResponse): Deleted.
* platform/network/SynchronousLoaderClient.h:
* platform/network/cf/ResourceHandleCFNet.cpp:
(WebCore::ResourceHandle::createCFURLConnection):
(WebCore::ResourceHandle::start):
(WebCore::ResourceHandle::willSendRequest):
(WebCore::ResourceHandle::shouldUseCredentialStorage):
(WebCore::ResourceHandle::canAuthenticateAgainstProtectionSpace):
(WebCore::ResourceHandle::platformLoadResourceSynchronously):
* platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp:
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::ResourceHandleCFURLConnectionDelegateWithOperationQueue):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::releaseHandle):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveData):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFinishLoading):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFail):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveChallenge):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didSendBodyData):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::shouldUseCredentialStorage):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueCanAuthenticateAgainstProtectionSpace):
* platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.h:
* platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp: Removed.
* platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.h: Removed.
* platform/network/mac/ResourceHandleMac.mm:
(WebCore::ResourceHandle::start):
(WebCore::ResourceHandle::schedule):
(WebCore::ResourceHandle::makeDelegate):
(WebCore::ResourceHandle::delegate):
(WebCore::ResourceHandle::platformLoadResourceSynchronously):
(WebCore::ResourceHandle::willSendRequest):
(WebCore::ResourceHandle::continueWillSendRequest):
(WebCore::ResourceHandle::continueDidReceiveResponse):
(WebCore::ResourceHandle::canAuthenticateAgainstProtectionSpace):
(WebCore::ResourceHandle::continueCanAuthenticateAgainstProtectionSpace):
(WebCore::ResourceHandle::continueWillCacheResponse):
(WebCore::ResourceHandle::shouldUseCredentialStorage): Deleted.
* platform/network/mac/WebCoreResourceHandleAsDelegate.h: Removed.
* platform/network/mac/WebCoreResourceHandleAsDelegate.mm: Removed.
* platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h:
* platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm:
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:willSendRequest:redirectResponse:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveAuthenticationChallenge:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:canAuthenticateAgainstProtectionSpace:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveResponse:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveData:lengthReceived:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:didFailWithError:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:willCacheResponse:]):

Source/WebKitLegacy:

* WebCoreSupport/WebResourceLoadScheduler.cpp:
(WebResourceLoadScheduler::createPingHandle):

Tools:

* TestWebKitAPI/Tests/mac/SimplifyMarkup.mm:
(TestWebKitAPI::TEST):
The HTML being loaded contains an iframe, so testing if the main resource has loaded doesn't necessarily mean all subresources are loaded.
Wait until they are loaded before continuing the test.  This is a test of editing commands once the page has loaded, not a test of loading.

LayoutTests:

* TestExpectations:
* platform/gtk/TestExpectations:
* platform/ios-wk2/TestExpectations:
* platform/mac-wk2/TestExpectations:
* platform/wk2/TestExpectations:

http/tests/cache/iframe-304-crash.html used to deterministically record its didFinishLoading callback,
but only for WK1.  It was marked as flaky for all WK2 ports.  It is now flaky in WK1 because the order
of the testRunner.notifyDone call and the didFinishLoading logging is no longer deterministic with
asynchronous loading, but the test still verifies that there is no crash.

http/tests/security/cross-origin-modal-dialog-base.html does navigation during showModalDialog, which
probably should've never worked in WK1 and never worked in WK2.  WK1 behavior now matches WK2 behavior.
I'm not aware of any complaints about no navigation working during showModalDialog in WK2 and I imagine
nobody will be regressed by this change, but if we do find such a problem, creative use of MessageQueues
like we do with sync xhr in WK1 now could theoretically fix the problem, but we are trying to get
rid of showModalDialog anyway.  The test was written to verify that the SecurityOrigin doesn't fall back
to the wrong origin, and it certainly doesn't now.

These tests dump load delegate call order, which are less deterministic now but the tests still behave correctly.
http/tests/svg/svg-use-external.html
http/tests/loading/text-content-type-with-binary-extension.html
http/tests/security/contentSecurityPolicy/block-all-mixed-content/insecure-iframe-in-main-frame.html

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@224267 268f45cc-cd09-0410-ab3c-d52691b4dbfc

56 files changed:
LayoutTests/ChangeLog
LayoutTests/TestExpectations
LayoutTests/platform/gtk/TestExpectations
LayoutTests/platform/ios-wk2/TestExpectations
LayoutTests/platform/mac-wk1/TestExpectations
LayoutTests/platform/mac-wk2/TestExpectations
LayoutTests/platform/wk2/TestExpectations
LayoutTests/security/block-test.html
LayoutTests/svg/in-html/by-reference.html
Source/WebCore/ChangeLog
Source/WebCore/PlatformAppleWin.cmake
Source/WebCore/PlatformMac.cmake
Source/WebCore/SourcesCocoa.txt
Source/WebCore/WebCore.xcodeproj/project.pbxproj
Source/WebCore/editing/cocoa/WebArchiveResourceFromNSAttributedString.mm
Source/WebCore/loader/ResourceLoader.cpp
Source/WebCore/loader/ResourceLoader.h
Source/WebCore/loader/appcache/ApplicationCacheGroup.cpp
Source/WebCore/loader/appcache/ApplicationCacheGroup.h
Source/WebCore/platform/network/BlobResourceHandle.cpp
Source/WebCore/platform/network/PingHandle.h
Source/WebCore/platform/network/ResourceHandle.cpp
Source/WebCore/platform/network/ResourceHandle.h
Source/WebCore/platform/network/ResourceHandleClient.cpp
Source/WebCore/platform/network/ResourceHandleClient.h
Source/WebCore/platform/network/ResourceHandleInternal.h
Source/WebCore/platform/network/SynchronousLoaderClient.cpp
Source/WebCore/platform/network/SynchronousLoaderClient.h
Source/WebCore/platform/network/cf/CookieJarCFNet.cpp
Source/WebCore/platform/network/cf/FormDataStreamCFNet.cpp
Source/WebCore/platform/network/cf/ResourceHandleCFNet.cpp
Source/WebCore/platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp
Source/WebCore/platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.h
Source/WebCore/platform/network/cf/ResourceRequestCFNet.cpp
Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp [deleted file]
Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.h [deleted file]
Source/WebCore/platform/network/curl/MultipartHandle.cpp
Source/WebCore/platform/network/curl/ResourceHandleCurl.cpp
Source/WebCore/platform/network/curl/ResourceHandleCurlDelegate.cpp
Source/WebCore/platform/network/mac/CookieJarMac.mm
Source/WebCore/platform/network/mac/ResourceHandleMac.mm
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.h [deleted file]
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.mm [deleted file]
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm
Source/WebCore/platform/network/soup/ResourceHandleSoup.cpp
Source/WebKit/NetworkProcess/Downloads/BlobDownloadClient.cpp
Source/WebKit/NetworkProcess/Downloads/BlobDownloadClient.h
Source/WebKit/NetworkProcess/NetworkConnectionToWebProcess.cpp
Source/WebKit/NetworkProcess/NetworkLoad.h
Source/WebKit/Shared/mac/ArgumentCodersMac.h
Source/WebKit/Shared/mac/WebCoreArgumentCodersMac.mm
Source/WebKitLegacy/ChangeLog
Source/WebKitLegacy/WebCoreSupport/WebResourceLoadScheduler.cpp
Tools/ChangeLog
Tools/TestWebKitAPI/Tests/mac/SimplifyMarkup.mm

index c6ad277..eda6360 100644 (file)
@@ -1,3 +1,34 @@
+2017-10-31  Alex Christensen  <achristensen@webkit.org>
+
+        Use asynchronous ResourceHandleClient calls for WebKit1
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+
+        Reviewed by Brady Eidson.
+
+        * TestExpectations:
+        * platform/gtk/TestExpectations:
+        * platform/ios-wk2/TestExpectations:
+        * platform/mac-wk2/TestExpectations:
+        * platform/wk2/TestExpectations:
+
+        http/tests/cache/iframe-304-crash.html used to deterministically record its didFinishLoading callback,
+        but only for WK1.  It was marked as flaky for all WK2 ports.  It is now flaky in WK1 because the order
+        of the testRunner.notifyDone call and the didFinishLoading logging is no longer deterministic with
+        asynchronous loading, but the test still verifies that there is no crash.
+
+        http/tests/security/cross-origin-modal-dialog-base.html does navigation during showModalDialog, which
+        probably should've never worked in WK1 and never worked in WK2.  WK1 behavior now matches WK2 behavior.
+        I'm not aware of any complaints about no navigation working during showModalDialog in WK2 and I imagine
+        nobody will be regressed by this change, but if we do find such a problem, creative use of MessageQueues
+        like we do with sync xhr in WK1 now could theoretically fix the problem, but we are trying to get
+        rid of showModalDialog anyway.  The test was written to verify that the SecurityOrigin doesn't fall back
+        to the wrong origin, and it certainly doesn't now.
+
+        These tests dump load delegate call order, which are less deterministic now but the tests still behave correctly.
+        http/tests/svg/svg-use-external.html
+        http/tests/loading/text-content-type-with-binary-extension.html
+        http/tests/security/contentSecurityPolicy/block-all-mixed-content/insecure-iframe-in-main-frame.html
+
 2017-10-31  Simon Fraser  <simon.fraser@apple.com>
 
         Rubber-banding overflow-scrolling-touch shows black
index 5d9a1d5..d0b824c 100644 (file)
@@ -40,6 +40,9 @@ http/tests/gzip-content-encoding [ Skip ]
 
 # window.showModalDialog is only tested in DumpRenderTree on Mac.
 editing/execCommand/show-modal-dialog-during-execCommand.html [ Skip ]
+http/tests/security/cross-origin-modal-dialog-base.html [ Skip ]
+fast/events/scroll-event-during-modal-dialog.html [ Skip ]
+fast/harness/show-modal-dialog.html [ Skip ]
 
 fast/shadow-dom/touch-event-on-text-assigned-to-slot.html [ Skip ]
 
@@ -489,6 +492,11 @@ webkit.org/b/169565 imported/w3c/web-platform-tests/cors/status-preflight.htm [
 webkit.org/b/169565 imported/w3c/web-platform-tests/cors/status-async.htm [ Failure ]
 webkit.org/b/169565 imported/w3c/web-platform-tests/cors/304.htm [ Failure ]
 
+# These tests used to have deterministic load delegate callback order before webkit.org/b/160677
+http/tests/svg/svg-use-external.html [ Pass Failure ]
+http/tests/loading/text-content-type-with-binary-extension.html [ Pass Failure ]
+http/tests/security/contentSecurityPolicy/block-all-mixed-content/insecure-iframe-in-main-frame.html [ Pass Failure ]
+
 # Tests that are flakey due to unhandled promise rejection error messages
 webkit.org/b/171094 imported/w3c/web-platform-tests/streams/readable-streams/tee.html [ Pass Failure ]
 webkit.org/b/171094 streams/brand-checks.html [ Pass Failure ]
@@ -825,6 +833,7 @@ webkit.org/b/139840 fast/xmlhttprequest/xmlhttprequest-recursive-sync-event.html
 
 webkit.org/b/140043 js/dom/Promise.html [ Pass Failure ]
 
+webkit.org/b/134550 http/tests/cache/iframe-304-crash.html [ Failure Pass ]
 webkit.org/b/141267 http/tests/misc/detached-frame-console.html [ Pass Failure ]
 
 # Aborting application cache abort tests are intrinsically flaky.
index a2df85c..612f5b4 100644 (file)
@@ -1633,8 +1633,6 @@ webkit.org/b/133869 media/video-seek-after-end.html [ Failure Pass ]
 # Crash is webkit.org/b/176802
 webkit.org/b/36642 fast/replaced/border-radius-clip.html [ Failure Pass Crash ]
 
-webkit.org/b/134550 http/tests/cache/iframe-304-crash.html [ Failure Pass ]
-
 webkit.org/b/134573 media/track/audio-track.html [ Failure Timeout Pass ]
 webkit.org/b/134576 media/track/audio/audio-track-mkv-vorbis-language.html [ Failure Timeout Pass ]
 webkit.org/b/134576 media/track/track-cue-rendering.html [ Failure Timeout Pass ]
index 152bff0..8273d8c 100644 (file)
@@ -367,7 +367,6 @@ http/tests/websocket/tests/hybi/invalid-subprotocol-characters.html
 http/tests/xmlhttprequest/cross-origin-authorization-with-embedder.html
 
 # HTTP tests that are flaky:
-http/tests/cache/iframe-304-crash.html [ Failure Pass ]
 http/tests/navigation/forward-and-cancel.html [ Failure Pass ]
 http/tests/security/xss-DENIED-xsl-external-entity-redirect.xml [ Failure Pass ]
 http/tests/webarchive/cross-origin-stylesheet-crash.html [ Failure Pass ]
index 4ff23cc..44f3b57 100644 (file)
@@ -74,6 +74,21 @@ webkit.org/b/155067 storage/indexeddb/transaction-abort-private.html [ Pass Cras
 
 webkit.org/b/172092 [ Debug ] fast/parser/adoption-agency-unload-iframe-4.html [ Pass Timeout ]
 
+# webkit.org/b/178272
+http/tests/media/video-redirect.html [ Pass Failure ]
+http/tests/security/contentSecurityPolicy/audio-redirect-allowed.html [ Pass Failure ]
+http/tests/security/contentSecurityPolicy/video-redirect-allowed.html [ Pass Failure ]
+http/tests/security/contentSecurityPolicy/video-with-http-url-allowed-by-csp-media-src-star.html [ Pass Failure ]
+http/tests/security/local-video-source-from-remote.html [ Pass Failure ]
+http/tests/security/video-cross-origin-accesssameorigin.html [ Pass Failure ]
+http/tests/canvas/webgl/origin-clean-conformance.html [ Pass Timeout ]
+http/tests/media/autoplay-if-audio-is-playing.html [ Pass Timeout ]
+http/tests/media/video-load-twice.html [ Pass Timeout ]
+http/tests/media/video-play-progress.html [ Pass Timeout ]
+http/tests/security/canvas-remote-read-remote-video-localhost.html [ Pass Timeout ]
+http/tests/security/canvas-remote-read-remote-video-redirect.html [ Pass Timeout ]
+http/tests/security/video-cross-origin-caching.html [ Pass Timeout ]
+
 ### END OF (1) Failures with bug reports
 ########################################
 
index 3be957e..7f1d6c0 100644 (file)
@@ -301,8 +301,6 @@ webkit.org/b/125996 accessibility/mac/search-when-element-starts-in-table.html [
 
 webkit.org/b/162999 accessibility/mac/wk1-set-selected-text-marker-range-input-element.html [ Skip ]
 
-webkit.org/b/134550 http/tests/cache/iframe-304-crash.html [ Pass Failure ]
-
 # testRunner.setUseDeferredFrameLoading is not implemented.
 webkit.org/b/93980 http/tests/appcache/load-from-appcache-defer-resume-crash.html [ Skip ]
 
index 402f73a..937e7b5 100644 (file)
@@ -264,7 +264,6 @@ http/tests/loading/cross-origin-XHR-willLoadRequest.html
 # WebKit2 needs showModalDialog
 fast/events/scroll-event-during-modal-dialog.html
 fast/harness/show-modal-dialog.html
-http/tests/security/cross-origin-modal-dialog-base.html [ Skip ]
 
 # WebKit2 needs to support synchronous creation of about:blank/data:url frames
 fast/dom/HTMLDocument/hasFocus.html
index edde932..1af639b 100644 (file)
             setTimeout("testRunner.notifyDone()", 0); 
         }
     }
+
+    function makeImage() {
+        var image = document.createElement("img");
+        image.onerror=nextBlockedPortTest;
+        image.src="http://255.255.255.255:1/test.jpg";
+        image.id="testIMG";
+        document.body.appendChild(image);
+    }
 </script>
-<body>
+<body onload="makeImage()">
 <p>This test attempts to change the src of an IMG tag to all black listed ports to confirm that WebKit returns the
 correct error for them - blocked instead of cannot find.  It also tries the FTP ports for exemptions.  Due to the 
 nature of this test, the results can only be processed automatically via DumpRenderTree
 </p>
-<img id="testIMG" src="http://255.255.255.255:1/test.jpg" onError="nextBlockedPortTest();"></img>
 </body>
 </html>
index 3b49cd5..874c18c 100644 (file)
@@ -4,6 +4,15 @@
   SVG documents included by reference should be transparent.  Any white visible in the green box is a failure.
 -->
 <head>
+    <script>
+        if (window.testRunner)
+            testRunner.waitUntilDone();
+        var elementsLoaded = 0;
+        function loaded() {
+            if (window.testRunner && ++elementsLoaded == 5)
+                testRunner.notifyDone();
+        }
+    </script>
   <style type='text/css'>
     * {
       margin: 0px;
 </head>
 <body>
   <div>
-    <object type='image/svg+xml' width='50' height='50' data='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></object>
-    <embed width='50' height='50' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></embed>
-    <iframe width='100' height='100' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></iframe>
-    <object type='text/xml' width='50' height='50' data='data:text/xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></object>
-    <object type='application/xml' width='50' height='50' data='data:application/xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></object-->
+    <object onload="loaded()" type='image/svg+xml' width='50' height='50' data='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></object>
+    <embed onload="loaded()" width='50' height='50' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></embed>
+    <iframe onload="loaded()" width='100' height='100' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></iframe>
+    <object onload="loaded()" type='text/xml' width='50' height='50' data='data:text/xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></object>
+    <object onload="loaded()" type='application/xml' width='50' height='50' data='data:application/xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjUwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4='></object-->
   </div>
 </body>
 </html>
index 5cc7d10..1b8b163 100644 (file)
@@ -1,3 +1,109 @@
+2017-10-31  Alex Christensen  <achristensen@webkit.org>
+
+        Use asynchronous ResourceHandleClient calls for WebKit1
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+
+        Reviewed by Brady Eidson.
+
+        Covered by existing tests.
+
+        * PlatformAppleWin.cmake:
+        * PlatformMac.cmake:
+        * WebCore.xcodeproj/project.pbxproj:
+        * loader/ResourceLoader.cpp:
+        (WebCore::ResourceLoader::willSendRequestAsync):
+        (WebCore::ResourceLoader::didReceiveResponseAsync):
+        (WebCore::ResourceLoader::canAuthenticateAgainstProtectionSpaceAsync):
+        * loader/ResourceLoader.h:
+        * loader/appcache/ApplicationCacheGroup.cpp:
+        (WebCore::ApplicationCacheGroup::didReceiveResponseAsync):
+        (WebCore::ApplicationCacheGroup::willSendRequestAsync):
+        (WebCore::ApplicationCacheGroup::canAuthenticateAgainstProtectionSpaceAsync):
+        (WebCore::ApplicationCacheGroup::didReceiveResponse): Deleted.
+        * loader/appcache/ApplicationCacheGroup.h:
+        * platform/network/BlobResourceHandle.cpp:
+        (WebCore::BlobResourceHandle::continueDidReceiveResponse):
+        (WebCore::BlobResourceHandle::getSizeForNext):
+        (WebCore::BlobResourceHandle::notifyResponseOnSuccess):
+        (WebCore::BlobResourceHandle::notifyResponseOnError):
+        * platform/network/PingHandle.h:
+        * platform/network/ResourceHandle.cpp:
+        (WebCore::ResourceHandle::didReceiveResponse):
+        (WebCore::ResourceHandle::usesAsyncCallbacks): Deleted.
+        * platform/network/ResourceHandle.h:
+        * platform/network/ResourceHandleClient.cpp:
+        (WebCore::ResourceHandleClient::~ResourceHandleClient):
+        (WebCore::ResourceHandleClient::willSendRequest): Deleted.
+        (WebCore::ResourceHandleClient::willSendRequestAsync): Deleted.
+        (WebCore::ResourceHandleClient::didReceiveResponseAsync): Deleted.
+        (WebCore::ResourceHandleClient::canAuthenticateAgainstProtectionSpaceAsync): Deleted.
+        * platform/network/ResourceHandleClient.h:
+        (WebCore::ResourceHandleClient::didReceiveAuthenticationChallenge):
+        (WebCore::ResourceHandleClient::didReceiveResponse): Deleted.
+        (WebCore::ResourceHandleClient::usesAsyncCallbacks): Deleted.
+        (WebCore::ResourceHandleClient::canAuthenticateAgainstProtectionSpace): Deleted.
+        * platform/network/ResourceHandleInternal.h:
+        (WebCore::ResourceHandleInternal::ResourceHandleInternal):
+        * platform/network/SynchronousLoaderClient.cpp:
+        (WebCore::SynchronousLoaderClient::willSendRequestAsync):
+        (WebCore::SynchronousLoaderClient::canAuthenticateAgainstProtectionSpaceAsync):
+        (WebCore::SynchronousLoaderClient::didReceiveResponseAsync):
+        (WebCore::SynchronousLoaderClient::didFinishLoading):
+        (WebCore::SynchronousLoaderClient::didFail):
+        (WebCore::SynchronousLoaderClient::willSendRequest): Deleted.
+        (WebCore::SynchronousLoaderClient::canAuthenticateAgainstProtectionSpace): Deleted.
+        (WebCore::SynchronousLoaderClient::didReceiveResponse): Deleted.
+        * platform/network/SynchronousLoaderClient.h:
+        * platform/network/cf/ResourceHandleCFNet.cpp:
+        (WebCore::ResourceHandle::createCFURLConnection):
+        (WebCore::ResourceHandle::start):
+        (WebCore::ResourceHandle::willSendRequest):
+        (WebCore::ResourceHandle::shouldUseCredentialStorage):
+        (WebCore::ResourceHandle::canAuthenticateAgainstProtectionSpace):
+        (WebCore::ResourceHandle::platformLoadResourceSynchronously):
+        * platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp:
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::ResourceHandleCFURLConnectionDelegateWithOperationQueue):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::releaseHandle):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveData):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFinishLoading):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFail):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveChallenge):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didSendBodyData):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::shouldUseCredentialStorage):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueCanAuthenticateAgainstProtectionSpace):
+        * platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.h:
+        * platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp: Removed.
+        * platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.h: Removed.
+        * platform/network/mac/ResourceHandleMac.mm:
+        (WebCore::ResourceHandle::start):
+        (WebCore::ResourceHandle::schedule):
+        (WebCore::ResourceHandle::makeDelegate):
+        (WebCore::ResourceHandle::delegate):
+        (WebCore::ResourceHandle::platformLoadResourceSynchronously):
+        (WebCore::ResourceHandle::willSendRequest):
+        (WebCore::ResourceHandle::continueWillSendRequest):
+        (WebCore::ResourceHandle::continueDidReceiveResponse):
+        (WebCore::ResourceHandle::canAuthenticateAgainstProtectionSpace):
+        (WebCore::ResourceHandle::continueCanAuthenticateAgainstProtectionSpace):
+        (WebCore::ResourceHandle::continueWillCacheResponse):
+        (WebCore::ResourceHandle::shouldUseCredentialStorage): Deleted.
+        * platform/network/mac/WebCoreResourceHandleAsDelegate.h: Removed.
+        * platform/network/mac/WebCoreResourceHandleAsDelegate.mm: Removed.
+        * platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h:
+        * platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm:
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:willSendRequest:redirectResponse:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveAuthenticationChallenge:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:canAuthenticateAgainstProtectionSpace:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveResponse:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveData:lengthReceived:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:didFailWithError:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:willCacheResponse:]):
+
 2017-10-31  Simon Fraser  <simon.fraser@apple.com>
 
         Rubber-banding overflow-scrolling-touch shows black
index fa08761..29a3199 100644 (file)
@@ -59,11 +59,11 @@ list(APPEND WebCore_SOURCES
     platform/network/cf/ResourceErrorCF.cpp
     platform/network/cf/ResourceHandleCFNet.cpp
     platform/network/cf/ResourceHandleCFURLConnectionDelegate.cpp
+    platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp
     platform/network/cf/ResourceRequestCFNet.cpp
     platform/network/cf/ResourceResponseCFNet.cpp
     platform/network/cf/SocketStreamHandleImplCFNet.cpp
     platform/network/cf/SynchronousLoaderClientCFNet.cpp
-    platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp
 )
 
 if (${USE_DIRECT2D})
index b676423..b58418a 100644 (file)
@@ -479,7 +479,6 @@ list(APPEND WebCore_SOURCES
     platform/network/mac/ResourceHandleMac.mm
     platform/network/mac/SynchronousLoaderClient.mm
     platform/network/mac/UTIUtilities.mm
-    platform/network/mac/WebCoreResourceHandleAsDelegate.mm
     platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm
     platform/network/mac/WebCoreURLResponse.mm
 
index 753ac88..ba1e576 100644 (file)
@@ -330,7 +330,6 @@ platform/network/cf/ResourceRequestCFNet.cpp
 platform/network/cf/ResourceResponseCFNet.cpp
 platform/network/cf/SocketStreamHandleImplCFNet.cpp
 platform/network/cf/SynchronousLoaderClientCFNet.cpp
-platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp
 
 platform/network/cocoa/CookieCocoa.mm
 platform/network/cocoa/CookieStorageObserver.mm
@@ -353,7 +352,6 @@ platform/network/mac/ResourceErrorMac.mm
 platform/network/mac/ResourceHandleMac.mm
 platform/network/mac/SynchronousLoaderClient.mm
 platform/network/mac/UTIUtilities.mm
-platform/network/mac/WebCoreResourceHandleAsDelegate.mm
 platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm
 platform/network/mac/WebCoreURLResponse.mm
 
index 183478a..078a3ab 100644 (file)
                26F9A83918A046AC00AEB88A /* ViewportConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = 26F9A83718A046AC00AEB88A /* ViewportConfiguration.h */; settings = {ATTRIBUTES = (Private, ); }; };
                26FAE4CC1852E3A5004C8C46 /* ResourceHandleCFURLConnectionDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 26FAE4C81852E3A5004C8C46 /* ResourceHandleCFURLConnectionDelegate.cpp */; };
                26FAE4CD1852E3A5004C8C46 /* ResourceHandleCFURLConnectionDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 26FAE4C91852E3A5004C8C46 /* ResourceHandleCFURLConnectionDelegate.h */; };
-               26FAE4CF1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 26FAE4CB1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h */; };
                2914E3081CAB5A440049966F /* AccessibilityAttachment.h in Headers */ = {isa = PBXBuildFile; fileRef = 2914E3061CAB5A440049966F /* AccessibilityAttachment.h */; };
                2917B5621473496C0052C9D0 /* LayerFlushScheduler.h in Headers */ = {isa = PBXBuildFile; fileRef = 2917B55F1473496C0052C9D0 /* LayerFlushScheduler.h */; settings = {ATTRIBUTES = (Private, ); }; };
                2917B5631473496C0052C9D0 /* LayerFlushSchedulerClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 2917B5601473496C0052C9D0 /* LayerFlushSchedulerClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
                E179F0DA1B9774FE00ED0A27 /* Internals.mm in Sources */ = {isa = PBXBuildFile; fileRef = E179F0D91B9774FE00ED0A27 /* Internals.mm */; };
                E17B491616A9B094001C8839 /* TransitionEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E17B491416A9B093001C8839 /* TransitionEvent.h */; };
                E17B492116A9B8FF001C8839 /* JSTransitionEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E17B491F16A9B8FF001C8839 /* JSTransitionEvent.h */; };
-               E180810F16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = E180810D16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h */; };
                E180811716FCF9CB00B80D07 /* SynchronousLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E180811516FCF9CB00B80D07 /* SynchronousLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
                E18256900EF2B02D00933242 /* JSWorkerGlobalScope.h in Headers */ = {isa = PBXBuildFile; fileRef = E182568E0EF2B02D00933242 /* JSWorkerGlobalScope.h */; };
                E18536841F4E481400FE091B /* WebArchiveResourceFromNSAttributedString.h in Headers */ = {isa = PBXBuildFile; fileRef = E18536811F4E472700FE091B /* WebArchiveResourceFromNSAttributedString.h */; };
                26F9A83718A046AC00AEB88A /* ViewportConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ViewportConfiguration.h; sourceTree = "<group>"; };
                26FAE4C81852E3A5004C8C46 /* ResourceHandleCFURLConnectionDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ResourceHandleCFURLConnectionDelegate.cpp; sourceTree = "<group>"; };
                26FAE4C91852E3A5004C8C46 /* ResourceHandleCFURLConnectionDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ResourceHandleCFURLConnectionDelegate.h; sourceTree = "<group>"; };
-               26FAE4CA1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SynchronousResourceHandleCFURLConnectionDelegate.cpp; sourceTree = "<group>"; };
-               26FAE4CB1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SynchronousResourceHandleCFURLConnectionDelegate.h; sourceTree = "<group>"; };
                2914E3051CAB5A440049966F /* AccessibilityAttachment.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AccessibilityAttachment.cpp; sourceTree = "<group>"; };
                2914E3061CAB5A440049966F /* AccessibilityAttachment.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AccessibilityAttachment.h; sourceTree = "<group>"; };
                2917B55E1473496C0052C9D0 /* LayerFlushScheduler.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LayerFlushScheduler.cpp; sourceTree = "<group>"; };
                E17B491416A9B093001C8839 /* TransitionEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TransitionEvent.h; sourceTree = "<group>"; };
                E17B491F16A9B8FF001C8839 /* JSTransitionEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSTransitionEvent.h; sourceTree = "<group>"; };
                E17B492016A9B8FF001C8839 /* JSTransitionEvent.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSTransitionEvent.cpp; sourceTree = "<group>"; };
-               E180810C16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WebCoreResourceHandleAsDelegate.mm; sourceTree = "<group>"; };
-               E180810D16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebCoreResourceHandleAsDelegate.h; sourceTree = "<group>"; };
                E180811016FCF42E00B80D07 /* SynchronousLoaderClient.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SynchronousLoaderClient.cpp; sourceTree = "<group>"; };
                E180811416FCF9CB00B80D07 /* SynchronousLoaderClient.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SynchronousLoaderClient.mm; sourceTree = "<group>"; };
                E180811516FCF9CB00B80D07 /* SynchronousLoaderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SynchronousLoaderClient.h; sourceTree = "<group>"; };
                                E180811416FCF9CB00B80D07 /* SynchronousLoaderClient.mm */,
                                1FAFBF1615A5FA5200083A20 /* UTIUtilities.h */,
                                1FAFBF1715A5FA5200083A20 /* UTIUtilities.mm */,
-                               E180810D16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h */,
-                               E180810C16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.mm */,
                                E152551316FD234F003D7ADB /* WebCoreResourceHandleAsOperationQueueDelegate.h */,
                                E152551416FD234F003D7ADB /* WebCoreResourceHandleAsOperationQueueDelegate.mm */,
                                37F818FB0D657606005E1F05 /* WebCoreURLResponse.h */,
                                51ABAE1C103C1913008C5260 /* SocketStreamHandleImpl.h */,
                                51ABAE1D103C1913008C5260 /* SocketStreamHandleImplCFNet.cpp */,
                                442ABCD517D9262F00D30715 /* SynchronousLoaderClientCFNet.cpp */,
-                               26FAE4CA1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.cpp */,
-                               26FAE4CB1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h */,
                        );
                        path = cf;
                        sourceTree = "<group>";
                                51F645971F4A686F00B54DED /* SWServerRegistration.h in Headers */,
                                517A53461F50C17F00DCDC0A /* SWServerWorker.h in Headers */,
                                E180811716FCF9CB00B80D07 /* SynchronousLoaderClient.h in Headers */,
-                               26FAE4CF1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h in Headers */,
                                0F03C0741884695E00A5F8CA /* SystemMemory.h in Headers */,
                                5D5975B319635F1100D00878 /* SystemVersion.h in Headers */,
                                A8CFF0510A154F09000A4234 /* TableLayout.h in Headers */,
                                CD225C0C1C46FBF400140761 /* WebCoreNSURLSession.h in Headers */,
                                DD05FE0D0B8BA3C6009ACDFE /* WebCoreObjCExtras.h in Headers */,
                                EDEC98030AED7E170059137F /* WebCorePrefix.h in Headers */,
-                               E180810F16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h in Headers */,
                                E152551516FD2350003D7ADB /* WebCoreResourceHandleAsOperationQueueDelegate.h in Headers */,
                                A14832C7187F66C800DA63A6 /* WebCoreThread.h in Headers */,
                                A14832C9187F676B00DA63A6 /* WebCoreThreadInternal.h in Headers */,
index a145664..9287efa 100644 (file)
@@ -42,7 +42,7 @@ using namespace WebCore;
         return nil;
     }
 
-    resource = ArchiveResource::create(SharedBuffer::create(adoptNS([data copy]).get()), URL, MIMEType, textEncodingName, frameName, nil);
+    resource = ArchiveResource::create(SharedBuffer::create(adoptNS([data copy]).get()), URL, MIMEType, textEncodingName, frameName, { });
     if (!resource) {
         [self release];
         return nil;
index e921427..39d64ea 100644 (file)
@@ -638,12 +638,15 @@ ResourceError ResourceLoader::cannotShowURLError()
     return frameLoader()->client().cannotShowURLError(m_request);
 }
 
-ResourceRequest ResourceLoader::willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&& redirectResponse)
+void ResourceLoader::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&& redirectResponse)
 {
-    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse))
-        return WTFMove(request);
+    RefPtr<ResourceHandle> protectedHandle(handle);
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse)) {
+        handle->continueWillSendRequest(WTFMove(request));
+        return;
+    }
     willSendRequestInternal(request, redirectResponse);
-    return WTFMove(request);
+    handle->continueWillSendRequest(WTFMove(request));
 }
 
 void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
@@ -651,11 +654,14 @@ void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent,
     didSendData(bytesSent, totalBytesToBeSent);
 }
 
-void ResourceLoader::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
+void ResourceLoader::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
 {
-    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response))
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response)) {
+        handle->continueDidReceiveResponse();
         return;
+    }
     didReceiveResponse(response);
+    handle->continueDidReceiveResponse();
 }
 
 void ResourceLoader::didReceiveData(ResourceHandle*, const char* data, unsigned length, int encodedDataLength)
@@ -726,6 +732,10 @@ void ResourceLoader::didReceiveAuthenticationChallenge(const AuthenticationChall
 }
 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+void ResourceLoader::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace& protectionSpace)
+{
+    handle->continueCanAuthenticateAgainstProtectionSpace(canAuthenticateAgainstProtectionSpace(protectionSpace));
+}
 
 bool ResourceLoader::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
 {
index f4c9a45..b672d0b 100644 (file)
@@ -184,9 +184,9 @@ private:
     void finishNetworkLoad();
 
     // ResourceHandleClient
-    ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&&, ResourceResponse&& redirectResponse) override;
     void didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) override;
-    void didReceiveResponse(ResourceHandle*, ResourceResponse&&) override;
+    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) override;
+    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
     void didReceiveData(ResourceHandle*, const char*, unsigned, int encodedDataLength) override;
     void didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&&, int encodedDataLength) override;
     void didFinishLoading(ResourceHandle*) override;
@@ -196,7 +196,7 @@ private:
     bool shouldUseCredentialStorage(ResourceHandle*) override { return shouldUseCredentialStorage(); }
     void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge) override { didReceiveAuthenticationChallenge(challenge); } 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace& protectionSpace) override { return canAuthenticateAgainstProtectionSpace(protectionSpace); }
+    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) override;
 #endif
     void receivedCancellation(ResourceHandle*, const AuthenticationChallenge& challenge) override { receivedCancellation(challenge); }
 #if PLATFORM(IOS)
index ee25f9f..113c687 100644 (file)
@@ -485,13 +485,14 @@ RefPtr<ResourceHandle> ApplicationCacheGroup::createResourceHandle(const URL& ur
     return handle;
 }
 
-void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, ResourceResponse&& response)
+void ApplicationCacheGroup::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
 {
     ASSERT(m_frame);
     InspectorInstrumentation::didReceiveResourceResponse(*m_frame, m_currentResourceIdentifier, m_frame->loader().documentLoader(), response, nullptr);
 
     if (handle == m_manifestHandle) {
         didReceiveManifestResponse(response);
+        handle->continueDidReceiveResponse();
         return;
     }
 
@@ -518,6 +519,7 @@ void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, ResourceR
             m_currentHandle = nullptr;
             // Load the next resource, if any.
             startLoadingEntry();
+            handle->continueDidReceiveResponse();
             return;
         }
         // The server could return 304 for an unconditional request - in this case, we handle the response as a normal error.
@@ -549,12 +551,26 @@ void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, ResourceR
             // Load the next resource, if any.
             startLoadingEntry();
         }
+        handle->continueDidReceiveResponse();
         return;
     }
     
     m_currentResource = ApplicationCacheResource::create(url, response, type);
+    handle->continueDidReceiveResponse();
 }
 
+void ApplicationCacheGroup::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&)
+{
+    handle->continueWillSendRequest(WTFMove(request));
+}
+
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+void ApplicationCacheGroup::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace&)
+{
+    handle->continueCanAuthenticateAgainstProtectionSpace(false);
+}
+#endif
+
 void ApplicationCacheGroup::didReceiveData(ResourceHandle* handle, const char* data, unsigned length, int encodedDataLength)
 {
     UNUSED_PARAM(encodedDataLength);
index 5373845..34aab9f 100644 (file)
@@ -109,10 +109,14 @@ private:
     bool shouldUseCredentialStorage(ResourceHandle*) override { return true; }
 
     // ResourceHandleClient
-    void didReceiveResponse(ResourceHandle*, ResourceResponse&&) override;
-    void didReceiveData(ResourceHandle*, const char*, unsigned length, int encodedDataLength) override;
-    void didFinishLoading(ResourceHandle*) override;
-    void didFail(ResourceHandle*, const ResourceError&) override;
+    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) final;
+    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) final;
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) final;
+#endif
+    void didReceiveData(ResourceHandle*, const char*, unsigned length, int encodedDataLength) final;
+    void didFinishLoading(ResourceHandle*) final;
+    void didFail(ResourceHandle*, const ResourceError&) final;
 
     void didReceiveManifestResponse(const ResourceResponse&);
     void didReceiveManifestData(const char*, int);
index 612969f..035eb49 100644 (file)
@@ -74,8 +74,12 @@ class BlobResourceSynchronousLoader : public ResourceHandleClient {
 public:
     BlobResourceSynchronousLoader(ResourceError&, ResourceResponse&, Vector<char>&);
 
-    void didReceiveResponse(ResourceHandle*, ResourceResponse&&) override;
-    void didFail(ResourceHandle*, const ResourceError&) override;
+    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) final;
+    void didFail(ResourceHandle*, const ResourceError&) final;
+    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) final;
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) final;
+#endif
 
 private:
     ResourceError& m_error;
@@ -90,11 +94,26 @@ BlobResourceSynchronousLoader::BlobResourceSynchronousLoader(ResourceError& erro
 {
 }
 
-void BlobResourceSynchronousLoader::didReceiveResponse(ResourceHandle* handle, ResourceResponse&& response)
+void BlobResourceSynchronousLoader::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&)
+{
+    ASSERT_NOT_REACHED();
+    handle->continueWillSendRequest(WTFMove(request));
+}
+
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+void BlobResourceSynchronousLoader::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace&)
+{
+    ASSERT_NOT_REACHED();
+    handle->continueCanAuthenticateAgainstProtectionSpace(false);
+}
+#endif
+
+void BlobResourceSynchronousLoader::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
 {
     // We cannot handle the size that is more than maximum integer.
     if (response.expectedContentLength() > INT_MAX) {
         m_error = ResourceError(webKitBlobResourceDomain, static_cast<int>(BlobResourceHandle::Error::NotReadableError), response.url(), "File is too large");
+        handle->continueDidReceiveResponse();
         return;
     }
 
@@ -103,6 +122,7 @@ void BlobResourceSynchronousLoader::didReceiveResponse(ResourceHandle* handle, R
     // Read all the data.
     m_data.resize(static_cast<size_t>(response.expectedContentLength()));
     static_cast<BlobResourceHandle*>(handle)->readSync(m_data.data(), static_cast<int>(m_data.size()));
+    handle->continueDidReceiveResponse();
 }
 
 void BlobResourceSynchronousLoader::didFail(ResourceHandle*, const ResourceError& error)
@@ -157,9 +177,6 @@ void BlobResourceHandle::cancel()
 
 void BlobResourceHandle::continueDidReceiveResponse()
 {
-    ASSERT(m_async);
-    ASSERT(usesAsyncCallbacks());
-
     m_buffer.resize(bufferSize);
     readAsync();
 }
@@ -226,10 +243,6 @@ void BlobResourceHandle::getSizeForNext()
         if (m_async) {
             Ref<BlobResourceHandle> protectedThis(*this);
             notifyResponse();
-            if (!usesAsyncCallbacks()) {
-                m_buffer.resize(bufferSize);
-                readAsync();
-            }
         }
         return;
     }
@@ -420,7 +433,6 @@ int BlobResourceHandle::readFileSync(const BlobDataItem& item, char* buf, int le
 void BlobResourceHandle::readAsync()
 {
     ASSERT(isMainThread());
-    ASSERT(m_async);
 
     // Do not continue if the request is aborted or an error occurs.
     if (erroredOrAborted())
@@ -444,7 +456,6 @@ void BlobResourceHandle::readAsync()
 void BlobResourceHandle::readDataAsync(const BlobDataItem& item)
 {
     ASSERT(isMainThread());
-    ASSERT(m_async);
     ASSERT(item.data().data());
 
     Ref<BlobResourceHandle> protectedThis(*this);
@@ -459,7 +470,6 @@ void BlobResourceHandle::readDataAsync(const BlobDataItem& item)
 void BlobResourceHandle::readFileAsync(const BlobDataItem& item)
 {
     ASSERT(isMainThread());
-    ASSERT(m_async);
 
     if (m_fileOpened) {
         m_asyncStream->read(m_buffer.data(), m_buffer.size());
@@ -573,7 +583,7 @@ void BlobResourceHandle::notifyResponseOnSuccess()
     // as if the response had a Content-Disposition header with the filename parameter set to the File's name attribute.
     // Notably, this will affect a name suggested in "File Save As".
 
-    didReceiveResponse(WTFMove(response));
+    client()->didReceiveResponseAsync(this, WTFMove(response));
 }
 
 void BlobResourceHandle::notifyResponseOnError()
@@ -596,7 +606,7 @@ void BlobResourceHandle::notifyResponseOnError()
         break;
     }
 
-    didReceiveResponse(WTFMove(response));
+    client()->didReceiveResponseAsync(this, WTFMove(response));
 }
 
 void BlobResourceHandle::notifyReceiveData(const char* data, int bytesRead)
index beb9c5a..3e91da2 100644 (file)
@@ -39,17 +39,11 @@ namespace WebCore {
 class PingHandle final : private ResourceHandleClient {
     WTF_MAKE_NONCOPYABLE(PingHandle); WTF_MAKE_FAST_ALLOCATED;
 public:
-    enum class UsesAsyncCallbacks {
-        Yes,
-        No,
-    };
-    
-    PingHandle(NetworkingContext* networkingContext, const ResourceRequest& request, bool shouldUseCredentialStorage, UsesAsyncCallbacks useAsyncCallbacks, bool shouldFollowRedirects, WTF::CompletionHandler<void(const ResourceError&, const ResourceResponse&)>&& completionHandler)
+    PingHandle(NetworkingContext* networkingContext, const ResourceRequest& request, bool shouldUseCredentialStorage, bool shouldFollowRedirects, WTF::CompletionHandler<void(const ResourceError&, const ResourceResponse&)>&& completionHandler)
         : m_currentRequest(request)
         , m_timeoutTimer(*this, &PingHandle::timeoutTimerFired)
         , m_shouldUseCredentialStorage(shouldUseCredentialStorage)
         , m_shouldFollowRedirects(shouldFollowRedirects)
-        , m_usesAsyncCallbacks(useAsyncCallbacks)
         , m_completionHandler(WTFMove(completionHandler))
     {
         m_handle = ResourceHandle::create(networkingContext, request, this, false, false);
@@ -60,26 +54,33 @@ public:
     }
 
 private:
-    ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&) final
-    {
-        return m_shouldFollowRedirects ? request : ResourceRequest();
-    }
-    void willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&) final
+    void willSendRequestAsync(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&) final
     {
         m_currentRequest = WTFMove(request);
         if (m_shouldFollowRedirects) {
-            handle->continueWillSendRequest(ResourceRequest { m_currentRequest });
+            m_handle->continueWillSendRequest(ResourceRequest { m_currentRequest });
             return;
         }
+        m_handle->continueWillSendRequest({ });
         pingLoadComplete(ResourceError { String(), 0, m_currentRequest.url(), ASCIILiteral("Not allowed to follow redirects"), ResourceError::Type::AccessControl });
     }
-    void didReceiveResponse(ResourceHandle*, ResourceResponse&& response) final { pingLoadComplete({ }, response); }
+    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&& response) final
+    {
+        m_handle->continueDidReceiveResponse();
+        pingLoadComplete({ }, response);
+    }
     void didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&&, int) final { pingLoadComplete(); }
     void didFinishLoading(ResourceHandle*) final { pingLoadComplete(); }
     void didFail(ResourceHandle*, const ResourceError& error) final { pingLoadComplete(error); }
     bool shouldUseCredentialStorage(ResourceHandle*) final { return m_shouldUseCredentialStorage; }
-    bool usesAsyncCallbacks() final { return m_usesAsyncCallbacks == UsesAsyncCallbacks::Yes; }
     void timeoutTimerFired() { pingLoadComplete(ResourceError { String(), 0, m_currentRequest.url(), ASCIILiteral("Load timed out"), ResourceError::Type::Timeout }); }
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&)
+    {
+        m_handle->continueCanAuthenticateAgainstProtectionSpace(false);
+        delete this;
+    }
+#endif
 
     void pingLoadComplete(const ResourceError& error = { }, const ResourceResponse& response = { })
     {
@@ -103,7 +104,6 @@ private:
     Timer m_timeoutTimer;
     bool m_shouldUseCredentialStorage;
     bool m_shouldFollowRedirects;
-    UsesAsyncCallbacks m_usesAsyncCallbacks;
     WTF::CompletionHandler<void(const ResourceError&, const ResourceResponse&)> m_completionHandler;
 };
 
index bebcf88..e6aa508 100644 (file)
@@ -159,15 +159,11 @@ void ResourceHandle::didReceiveResponse(ResourceResponse&& response)
             cancel();
             String message = "Cancelled load from '" + url.stringCenterEllipsizedToLength() + "' because it is using HTTP/0.9.";
             d->m_client->didFail(this, { String(), 0, url, message });
+            continueDidReceiveResponse();
             return;
         }
     }
-    if (d->m_usesAsyncCallbacks)
-        d->m_client->didReceiveResponseAsync(this, WTFMove(response));
-    else {
-        d->m_client->didReceiveResponse(this, WTFMove(response));
-        platformContinueSynchronousDidReceiveResponse();
-    }
+    client()->didReceiveResponseAsync(this, WTFMove(response));
 }
 
 #if !USE(SOUP) && !USE(CURL)
@@ -244,9 +240,4 @@ void ResourceHandle::setDefersLoading(bool defers)
     platformSetDefersLoading(defers);
 }
 
-bool ResourceHandle::usesAsyncCallbacks() const
-{
-    return d->m_usesAsyncCallbacks;
-}
-
 } // namespace WebCore
index 9e796f1..cc196d8 100644 (file)
@@ -70,6 +70,7 @@ typedef const struct __CFURLStorageSession* CFURLStorageSessionRef;
 
 namespace WTF {
 class SchedulePair;
+template<typename T> class MessageQueue;
 }
 
 namespace WebCore {
@@ -125,7 +126,7 @@ public:
 
 #if PLATFORM(COCOA) && !USE(CFURLCONNECTION)
     WEBCORE_EXPORT NSURLConnection *connection() const;
-    id makeDelegate(bool);
+    id makeDelegate(bool, WTF::MessageQueue<WTF::Function<void()>>*);
     id delegate();
     void releaseDelegate();
 #endif
@@ -237,8 +238,6 @@ public:
 protected:
     ResourceHandle(NetworkingContext*, const ResourceRequest&, ResourceHandleClient*, bool defersLoading, bool shouldContentSniff);
 
-    bool usesAsyncCallbacks() const;
-
 private:
     enum FailureType {
         NoFailure,
@@ -267,7 +266,7 @@ private:
 #endif
 
 #if USE(CFURLCONNECTION)
-    void createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, SchedulingBehavior, CFDictionaryRef clientProperties);
+    void createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, WTF::MessageQueue<WTF::Function<void()>>*, CFDictionaryRef clientProperties);
 #endif
 
 #if PLATFORM(MAC) && !USE(CFURLCONNECTION)
index e919df8..af5c418 100644 (file)
@@ -35,28 +35,6 @@ namespace WebCore {
 ResourceHandleClient::ResourceHandleClient() = default;
 
 ResourceHandleClient::~ResourceHandleClient() = default;
-    
-ResourceRequest ResourceHandleClient::willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&)
-{
-    return WTFMove(request);
-}
-
-void ResourceHandleClient::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&& /*redirectResponse*/)
-{
-    handle->continueWillSendRequest(WTFMove(request));
-}
-
-void ResourceHandleClient::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&&)
-{
-    handle->continueDidReceiveResponse();
-}
-
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-void ResourceHandleClient::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace&)
-{
-    handle->continueCanAuthenticateAgainstProtectionSpace(false);
-}
-#endif
 
 #if USE(CFURLCONNECTION)
 void ResourceHandleClient::willCacheResponseAsync(ResourceHandle* handle, CFCachedURLResponseRef response)
index 2618939..3912665 100644 (file)
@@ -63,11 +63,8 @@ public:
     WEBCORE_EXPORT ResourceHandleClient();
     WEBCORE_EXPORT virtual ~ResourceHandleClient();
 
-    WEBCORE_EXPORT virtual ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&&, ResourceResponse&&);
     virtual void didSendData(ResourceHandle*, unsigned long long /*bytesSent*/, unsigned long long /*totalBytesToBeSent*/) { }
 
-    virtual void didReceiveResponse(ResourceHandle*, ResourceResponse&&) { }
-    
     virtual void didReceiveData(ResourceHandle*, const char*, unsigned, int /*encodedDataLength*/) { }
     WEBCORE_EXPORT virtual void didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&&, int encodedDataLength);
     
@@ -76,19 +73,17 @@ public:
     virtual void wasBlocked(ResourceHandle*) { }
     virtual void cannotShowURL(ResourceHandle*) { }
 
-    virtual bool usesAsyncCallbacks() { return false; }
-
     virtual bool loadingSynchronousXHR() { return false; }
 
     // Client will pass an updated request using ResourceHandle::continueWillSendRequest() when ready.
-    WEBCORE_EXPORT virtual void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&);
+    WEBCORE_EXPORT virtual void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) = 0;
 
     // Client will call ResourceHandle::continueDidReceiveResponse() when ready.
-    WEBCORE_EXPORT virtual void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&);
+    WEBCORE_EXPORT virtual void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) = 0;
 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
     // Client will pass an updated request using ResourceHandle::continueCanAuthenticateAgainstProtectionSpace() when ready.
-    WEBCORE_EXPORT virtual void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&);
+    WEBCORE_EXPORT virtual void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) = 0;
 #endif
     // Client will pass an updated request using ResourceHandle::continueWillCacheResponse() when ready.
 #if USE(CFURLCONNECTION)
@@ -103,9 +98,6 @@ public:
 
     virtual bool shouldUseCredentialStorage(ResourceHandle*) { return false; }
     virtual void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge&) { }
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    virtual bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&) { return false; }
-#endif
     virtual void receivedCancellation(ResourceHandle*, const AuthenticationChallenge&) { }
 
 #if PLATFORM(IOS) || USE(CFURLCONNECTION)
index 3b7144b..fbb6cad 100644 (file)
@@ -80,7 +80,6 @@ public:
         , m_partition(request.cachePartition())
         , m_defersLoading(defersLoading)
         , m_shouldContentSniff(shouldContentSniff)
-        , m_usesAsyncCallbacks(client && client->usesAsyncCallbacks())
 #if USE(CFURLCONNECTION)
         , m_currentRequest(request)
 #endif
@@ -115,7 +114,6 @@ public:
 
     bool m_defersLoading;
     bool m_shouldContentSniff;
-    bool m_usesAsyncCallbacks;
 #if USE(CFURLCONNECTION)
     RetainPtr<CFURLConnectionRef> m_connection;
     ResourceRequest m_currentRequest;
index ce7539a..f9f28d8 100644 (file)
@@ -34,16 +34,17 @@ namespace WebCore {
 
 SynchronousLoaderClient::~SynchronousLoaderClient() = default;
 
-ResourceRequest SynchronousLoaderClient::willSendRequest(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&)
+void SynchronousLoaderClient::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&)
 {
     // FIXME: This needs to be fixed to follow the redirect correctly even for cross-domain requests.
-    if (protocolHostAndPortAreEqual(handle->firstRequest().url(), request.url()))
-        return WTFMove(request);
+    if (protocolHostAndPortAreEqual(handle->firstRequest().url(), request.url())) {
+        handle->continueWillSendRequest(WTFMove(request));
+        return;
+    }
 
     ASSERT(m_error.isNull());
     m_error = platformBadResponseError();
-    m_isDone = true;
-    return { };
+    handle->continueWillSendRequest({ });
 }
 
 bool SynchronousLoaderClient::shouldUseCredentialStorage(ResourceHandle*)
@@ -53,16 +54,17 @@ bool SynchronousLoaderClient::shouldUseCredentialStorage(ResourceHandle*)
 }
 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-bool SynchronousLoaderClient::canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&)
+void SynchronousLoaderClient::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace&)
 {
     // FIXME: We should ask FrameLoaderClient. <http://webkit.org/b/65196>
-    return true;
+    handle->continueCanAuthenticateAgainstProtectionSpace(true);
 }
 #endif
 
-void SynchronousLoaderClient::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
+void SynchronousLoaderClient::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
 {
     m_response = WTFMove(response);
+    handle->continueDidReceiveResponse();
 }
 
 void SynchronousLoaderClient::didReceiveData(ResourceHandle*, const char* data, unsigned length, int /*encodedDataLength*/)
@@ -72,7 +74,7 @@ void SynchronousLoaderClient::didReceiveData(ResourceHandle*, const char* data,
 
 void SynchronousLoaderClient::didFinishLoading(ResourceHandle*)
 {
-    m_isDone = true;
+    m_messageQueue.kill();
 }
 
 void SynchronousLoaderClient::didFail(ResourceHandle*, const ResourceError& error)
@@ -80,7 +82,8 @@ void SynchronousLoaderClient::didFail(ResourceHandle*, const ResourceError& erro
     ASSERT(m_error.isNull());
 
     m_error = error;
-    m_isDone = true;
+    
+    m_messageQueue.kill();
 }
 
 }
index cb9b309..be9e73d 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef SynchronousLoaderClient_h
-#define SynchronousLoaderClient_h
+#pragma once
 
 #include "ResourceError.h"
 #include "ResourceHandleClient.h"
 #include "ResourceResponse.h"
+#include <wtf/Function.h>
+#include <wtf/MessageQueue.h>
 
 namespace WebCore {
 
@@ -40,28 +41,26 @@ public:
     const ResourceResponse& response() const { return m_response; }
     Vector<char>& mutableData() { return m_data; }
     const ResourceError& error() const { return m_error; }
-    bool isDone() { return m_isDone; }
+    MessageQueue<Function<void()>>& messageQueue() { return m_messageQueue; }
 
     WEBCORE_EXPORT static ResourceError platformBadResponseError();
 
 private:
-    ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
+    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
     bool shouldUseCredentialStorage(ResourceHandle*) override;
     void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge&) override;
-    void didReceiveResponse(ResourceHandle*, ResourceResponse&&) override;
+    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) override;
     void didReceiveData(ResourceHandle*, const char*, unsigned, int /*encodedDataLength*/) override;
     void didFinishLoading(ResourceHandle*) override;
     void didFail(ResourceHandle*, const ResourceError&) override;
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&) override;
+    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) override;
 #endif
 
     bool m_allowStoredCredentials { false };
     ResourceResponse m_response;
     Vector<char> m_data;
     ResourceError m_error;
-    bool m_isDone { false };
+    MessageQueue<Function<void()>> m_messageQueue;
 };
 }
-
-#endif // SynchronousLoaderClient_h
index 90c7c89..49a9248 100644 (file)
@@ -59,7 +59,14 @@ struct CFTypeTrait<ClassName##Ref> { \
 static inline CFTypeID typeID() { return ClassName##GetTypeID(); } \
 };
 
+#if COMPILER(CLANG)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
 DECLARE_CF_TYPE_TRAIT(CFHTTPCookie);
+#if COMPILER(CLANG)
+#pragma clang diagnostic pop
+#endif
 
 #undef DECLARE_CF_TYPE_TRAIT
 } // namespace WTF
index 9383824..d8b45b3 100644 (file)
@@ -303,8 +303,8 @@ static CFTypeRef formCopyProperty(CFReadStreamRef, CFStringRef propertyName, voi
     FormStreamFields* form = static_cast<FormStreamFields*>(context);
 
     if (kCFCompareEqualTo == CFStringCompare(propertyName, formDataPointerPropertyName, 0)) {
-        long formDataAsNumber = static_cast<long>(reinterpret_cast<intptr_t>(form->formData.get()));
-        return CFNumberCreate(0, kCFNumberLongType, &formDataAsNumber);
+        long long formDataAsNumber = static_cast<long long>(reinterpret_cast<intptr_t>(form->formData.get()));
+        return CFNumberCreate(0, kCFNumberLongLongType, &formDataAsNumber);
     }
 
     if (kCFCompareEqualTo == CFStringCompare(propertyName, formDataStreamLengthPropertyName(), 0))
index 63fce8b..7a6c2ff 100644 (file)
 #include "NetworkStorageSession.h"
 #include "NetworkingContext.h"
 #include "ResourceError.h"
+#include "ResourceHandleCFURLConnectionDelegateWithOperationQueue.h"
 #include "ResourceHandleClient.h"
 #include "ResourceResponse.h"
 #include "SharedBuffer.h"
 #include "SynchronousLoaderClient.h"
-#include "SynchronousResourceHandleCFURLConnectionDelegate.h"
 #include <CFNetwork/CFNetwork.h>
 #include <pal/spi/cf/CFNetworkSPI.h>
 #include <sys/stat.h>
@@ -126,7 +126,7 @@ static inline CFStringRef shouldSniffConnectionProperty()
 #endif
 }
 
-void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, SchedulingBehavior schedulingBehavior, CFDictionaryRef clientProperties)
+void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, MessageQueue<Function<void()>>* messageQueue, CFDictionaryRef clientProperties)
 {
     if ((!d->m_user.isEmpty() || !d->m_pass.isEmpty()) && !firstRequest().url().protocolIsInHTTPFamily()) {
         // Credentials for ftp can only be passed in URL, the didReceiveAuthenticationChallenge delegate call won't be made.
@@ -203,15 +203,6 @@ void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool
         CFDictionarySetValue(streamProperties, CFSTR("_kCFURLConnectionSessionID"), CFSTR("WebKitPrivateSession"));
     }
 
-    if (schedulingBehavior == SchedulingBehavior::Synchronous) {
-        // Synchronous requests should not be subject to regular connection count limit to avoid deadlocks.
-        // If we are using all available connections for async requests, and make a sync request, then prior
-        // requests may get stuck waiting for delegate calls while we are in nested run loop, and the sync
-        // request won't start because there are no available connections.
-        // Connections are grouped by their socket stream properties, with each group having a separate count.
-        CFDictionarySetValue(streamProperties, CFSTR("_WebKitSynchronousRequest"), kCFBooleanTrue);
-    }
-
 #if PLATFORM(COCOA)
     RetainPtr<CFDataRef> sourceApplicationAuditData = d->m_context->sourceApplicationAuditData();
     if (sourceApplicationAuditData)
@@ -237,14 +228,7 @@ void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool
     CFDictionaryAddValue(propertiesDictionary.get(), kCFURLConnectionSocketStreamProperties, streamProperties);
     CFRelease(streamProperties);
 
-#if PLATFORM(COCOA)
-    if (d->m_usesAsyncCallbacks)
-        d->m_connectionDelegate = adoptRef(new ResourceHandleCFURLConnectionDelegateWithOperationQueue(this));
-    else
-        d->m_connectionDelegate = adoptRef(new SynchronousResourceHandleCFURLConnectionDelegate(this));
-#else
-    d->m_connectionDelegate = adoptRef(new SynchronousResourceHandleCFURLConnectionDelegate(this));
-#endif
+    d->m_connectionDelegate = adoptRef(new ResourceHandleCFURLConnectionDelegateWithOperationQueue(this, messageQueue));
     d->m_connectionDelegate->setupRequest(request.get());
 
     CFURLConnectionClient_V6 client = d->m_connectionDelegate->makeConnectionClient();
@@ -275,9 +259,8 @@ bool ResourceHandle::start()
     setCollectsTimingData();
 #endif
 
-    SchedulingBehavior schedulingBehavior = client()->loadingSynchronousXHR() ? SchedulingBehavior::Synchronous : SchedulingBehavior::Asynchronous;
-
-    createCFURLConnection(shouldUseCredentialStorage, d->m_shouldContentSniff, schedulingBehavior, client()->connectionProperties(this).get());
+    createCFURLConnection(shouldUseCredentialStorage, d->m_shouldContentSniff, nullptr, client()->connectionProperties(this).get());
+    ref();
 
     d->m_connectionDelegate->setupConnectionScheduling(d->m_connection.get());
     CFURLConnectionStart(d->m_connection.get());
@@ -325,29 +308,15 @@ ResourceRequest ResourceHandle::willSendRequest(ResourceRequest&& request, Resou
     }
 
     Ref<ResourceHandle> protectedThis(*this);
-    if (d->m_usesAsyncCallbacks) {
-        client()->willSendRequestAsync(this, WTFMove(request), WTFMove(redirectResponse));
-        return { };
-    }
-    
-    auto newRequest = client()->willSendRequest(this, WTFMove(request), WTFMove(redirectResponse));
-
-    // Client call may not preserve the session, especially if the request is sent over IPC.
-    if (!newRequest.isNull()) {
-        newRequest.setStorageSession(d->m_storageSession.get());
-
-        d->m_currentRequest = newRequest;
-    }
-    return newRequest;
+    client()->willSendRequestAsync(this, WTFMove(request), WTFMove(redirectResponse));
+    return { };
 }
 
 bool ResourceHandle::shouldUseCredentialStorage()
 {
     LOG(Network, "CFNet - shouldUseCredentialStorage()");
-    if (ResourceHandleClient* client = this->client()) {
-        ASSERT(!d->m_usesAsyncCallbacks);
+    if (ResourceHandleClient* client = this->client())
         return client->shouldUseCredentialStorage(this);
-    }
     return false;
 }
 
@@ -443,16 +412,11 @@ bool ResourceHandle::tryHandlePasswordBasedAuthentication(const AuthenticationCh
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
 {
-    ResourceHandleClient* client = this->client();
-    if (d->m_usesAsyncCallbacks) {
-        if (client)
-            client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
-        else
-            continueCanAuthenticateAgainstProtectionSpace(false);
-        return false; // Ignored by caller.
-    }
-
-    return client && client->canAuthenticateAgainstProtectionSpace(this, protectionSpace);
+    if (auto* client = this->client())
+        client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
+    else
+        continueCanAuthenticateAgainstProtectionSpace(false);
+    return false; // Ignored by caller.
 }
 #endif
 
@@ -574,6 +538,10 @@ CFStringRef ResourceHandle::synchronousLoadRunLoopMode()
     return CFSTR("WebCoreSynchronousLoaderRunLoopMode");
 }
 
+static void emptyPerform(void*)
+{
+}
+
 void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentialsPolicy storedCredentialsPolicy, ResourceError& error, ResourceResponse& response, Vector<char>& data)
 {
     LOG(Network, "ResourceHandle::platformLoadResourceSynchronously:%s sstoredCredentialsPolicy:%u", request.url().string().utf8().data(), static_cast<unsigned>(storedCredentialsPolicy));
@@ -595,19 +563,39 @@ void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* contex
         return;
     }
 
-    handle->createCFURLConnection(storedCredentialsPolicy == StoredCredentialsPolicy::Use, ResourceHandle::shouldContentSniffURL(request.url()),
-        SchedulingBehavior::Synchronous, handle->client()->connectionProperties(handle.get()).get());
-
-    CFURLConnectionScheduleWithRunLoop(handle->connection(), CFRunLoopGetCurrent(), synchronousLoadRunLoopMode());
-    CFURLConnectionScheduleDownloadWithRunLoop(handle->connection(), CFRunLoopGetCurrent(), synchronousLoadRunLoopMode());
+    handle->ref();
+    handle->createCFURLConnection(storedCredentialsPolicy == StoredCredentialsPolicy::Use, ResourceHandle::shouldContentSniffURL(request.url()), &client.messageQueue(), handle->client()->connectionProperties(handle.get()).get());
+
+    static CFRunLoopRef runLoop = nullptr;
+    if (!runLoop) {
+        BinarySemaphore sem;
+        Thread::create("CFNetwork Loader", [&] {
+            runLoop = CFRunLoopGetCurrent();
+
+            // Must add a source to the run loop to prevent CFRunLoopRun() from exiting.
+            CFRunLoopSourceContext ctxt = { 0, (void*)1 /*must be non-null*/, 0, 0, 0, 0, 0, 0, 0, emptyPerform };
+            CFRunLoopSourceRef bogusSource = CFRunLoopSourceCreate(0, 0, &ctxt);
+            CFRunLoopAddSource(runLoop, bogusSource, kCFRunLoopDefaultMode);
+            sem.signal();
+
+            while (true)
+                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1E30, true);
+        });
+        sem.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    }
+    CFURLConnectionScheduleWithRunLoop(handle->connection(), runLoop, kCFRunLoopDefaultMode);
+    CFURLConnectionScheduleDownloadWithRunLoop(handle->connection(), runLoop, kCFRunLoopDefaultMode);
     CFURLConnectionStart(handle->connection());
 
-    while (!client.isDone())
-        CFRunLoopRunInMode(synchronousLoadRunLoopMode(), UINT_MAX, true);
+    do {
+        if (auto task = client.messageQueue().waitForMessage())
+            (*task)();
+    } while (!client.messageQueue().killed());
 
     error = client.error();
 
-    CFURLConnectionCancel(handle->connection());
+    if (handle->connection())
+        CFURLConnectionCancel(handle->connection());
 
     if (error.isNull())
         response = client.response();
index 41c5dc5..8742c8a 100644 (file)
 #include "AuthenticationCF.h"
 #include "AuthenticationChallenge.h"
 #include "Logging.h"
+#include "MIMETypeRegistry.h"
 #include "ResourceHandle.h"
 #include "ResourceHandleClient.h"
 #include "ResourceResponse.h"
 #include "SharedBuffer.h"
+#if !PLATFORM(WIN)
 #include "WebCoreURLResponse.h"
+#endif
 #include <pal/spi/cf/CFNetworkSPI.h>
 #include <wtf/MainThread.h>
+#include <wtf/Threading.h>
 #include <wtf/text/CString.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebCore {
 
-ResourceHandleCFURLConnectionDelegateWithOperationQueue::ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle* handle)
+ResourceHandleCFURLConnectionDelegateWithOperationQueue::ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle* handle, MessageQueue<Function<void()>>* messageQueue)
     : ResourceHandleCFURLConnectionDelegate(handle)
-    , m_queue(dispatch_queue_create("com.apple.WebCore/CFNetwork", DISPATCH_QUEUE_SERIAL))
-    , m_semaphore(dispatch_semaphore_create(0))
+    , m_messageQueue(messageQueue)
 {
-    dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
-    dispatch_set_target_queue(m_queue, backgroundQueue);
 }
 
 ResourceHandleCFURLConnectionDelegateWithOperationQueue::~ResourceHandleCFURLConnectionDelegateWithOperationQueue()
 {
-    dispatch_release(m_semaphore);
-    dispatch_release(m_queue);
 }
 
 bool ResourceHandleCFURLConnectionDelegateWithOperationQueue::hasHandle() const
@@ -68,8 +67,7 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::releaseHandle()
     ResourceHandleCFURLConnectionDelegate::releaseHandle();
     m_requestResult = nullptr;
     m_cachedResponseResult = nullptr;
-    m_boolResult = false;
-    dispatch_semaphore_signal(m_semaphore);
+    m_semaphore.signal();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::setupRequest(CFMutableURLRequestRef request)
@@ -83,9 +81,62 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::setupRequest(CFMut
     m_originalScheme = adoptCF(CFURLCopyScheme(requestURL));
 }
 
+#if PLATFORM(WIN)
+LRESULT CALLBACK hookToRemoveCFNetworkMessage(int code, WPARAM wParam, LPARAM lParam)
+{
+    MSG* msg = reinterpret_cast<MSG*>(lParam);
+    // This message which CFNetwork sends to itself, will block the main thread, remove it.
+    if (msg->message == WM_USER + 0xcf)
+        msg->message = WM_NULL;
+    return CallNextHookEx(nullptr, code, wParam, lParam);
+}
+
+static void installHookToRemoveCFNetworkMessageBlockingMainThread()
+{
+    static HHOOK hook = nullptr;
+    if (!hook) {
+        DWORD threadID = ::GetCurrentThreadId();
+        hook = ::SetWindowsHookExW(WH_GETMESSAGE, hookToRemoveCFNetworkMessage, 0, threadID);
+    }
+}
+#endif
+
+static void emptyPerform(void*)
+{
+}
+
+static CFRunLoopRef getRunLoop()
+{
+    static CFRunLoopRef runLoop = nullptr;
+
+    if (!runLoop) {
+        BinarySemaphore sem;
+        Thread::create("CFNetwork Loader", [&] {
+            runLoop = CFRunLoopGetCurrent();
+
+            // Must add a source to the run loop to prevent CFRunLoopRun() from exiting.
+            CFRunLoopSourceContext ctxt = { 0, (void*)1 /*must be non-null*/, 0, 0, 0, 0, 0, 0, 0, emptyPerform };
+            CFRunLoopSourceRef bogusSource = CFRunLoopSourceCreate(0, 0, &ctxt);
+            CFRunLoopAddSource(runLoop, bogusSource, kCFRunLoopDefaultMode);
+            sem.signal();
+
+            while (true)
+                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1E30, true);
+        });
+        sem.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    }
+
+    return runLoop;
+}
+
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::setupConnectionScheduling(CFURLConnectionRef connection)
 {
-    CFURLConnectionSetDelegateDispatchQueue(connection, m_queue);
+#if PLATFORM(WIN)
+    installHookToRemoveCFNetworkMessageBlockingMainThread();
+#endif
+    CFRunLoopRef runLoop = getRunLoop();
+    CFURLConnectionScheduleWithRunLoop(connection, runLoop, kCFRunLoopDefaultMode);
+    CFURLConnectionScheduleDownloadWithRunLoop(connection, runLoop, kCFRunLoopDefaultMode);
 }
 
 CFURLRequestRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest(CFURLRequestRef cfRequest, CFURLResponseRef originalRedirectResponse)
@@ -101,17 +152,8 @@ CFURLRequestRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSen
 
     ASSERT(!isMainThread());
     
-    struct ProtectedParameters {
-        Ref<ResourceHandleCFURLConnectionDelegateWithOperationQueue> protectedThis;
-        RetainPtr<CFURLRequestRef> cfRequest;
-        RetainPtr<CFURLResponseRef> originalRedirectResponse;
-    };
-    
-    auto work = [] (void* context) {
-        auto& parameters = *reinterpret_cast<ProtectedParameters*>(context);
-        auto& protectedThis = parameters.protectedThis;
+    auto work = [protectedThis = makeRef(*this), cfRequest = RetainPtr<CFURLRequestRef>(cfRequest), originalRedirectResponse = RetainPtr<CFURLResponseRef>(originalRedirectResponse)] () {
         auto& handle = protectedThis->m_handle;
-        auto& cfRequest = parameters.cfRequest;
         
         if (!protectedThis->hasHandle()) {
             protectedThis->continueWillSendRequest(nullptr);
@@ -120,35 +162,28 @@ CFURLRequestRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSen
 
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
-        RetainPtr<CFURLResponseRef> redirectResponse = protectedThis->synthesizeRedirectResponseIfNecessary(cfRequest.get(), parameters.originalRedirectResponse.get());
+        RetainPtr<CFURLResponseRef> redirectResponse = protectedThis->synthesizeRedirectResponseIfNecessary(cfRequest.get(), originalRedirectResponse.get());
         ASSERT(redirectResponse);
 
         ResourceRequest request = protectedThis->createResourceRequest(cfRequest.get(), redirectResponse.get());
         handle->willSendRequest(WTFMove(request), redirectResponse.get());
     };
     
-    ProtectedParameters parameters { makeRef(*this), cfRequest, originalRedirectResponse };
-    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
+    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
 
     return m_requestResult.leakRef();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse(CFURLConnectionRef connection, CFURLResponseRef cfResponse)
 {
-    struct ProtectedParameters {
-        Ref<ResourceHandleCFURLConnectionDelegateWithOperationQueue> protectedThis;
-        RetainPtr<CFURLConnectionRef> connection;
-        RetainPtr<CFURLResponseRef> cfResponse;
-    };
-    
-    auto work = [] (void* context) {
-        auto& parameters = *reinterpret_cast<ProtectedParameters*>(context);
-        auto& protectedThis = parameters.protectedThis;
+    auto work = [protectedThis = makeRef(*this), cfResponse = RetainPtr<CFURLResponseRef>(cfResponse), connection = RetainPtr<CFURLConnectionRef>(connection)] () {
         auto& handle = protectedThis->m_handle;
-        auto& cfResponse = parameters.cfResponse;
         
-        if (!protectedThis->hasHandle() || !handle->client()) {
+        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
             protectedThis->continueDidReceiveResponse();
             return;
         }
@@ -161,7 +196,9 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse
 
         if (statusCode != 304) {
             bool isMainResourceLoad = handle->firstRequest().requester() == ResourceRequest::Requester::Main;
+#if !PLATFORM(WIN)
             adjustMIMETypeIfNecessary(cfResponse.get(), isMainResourceLoad);
+#endif
         }
 
 #if !PLATFORM(IOS)
@@ -170,86 +207,127 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse
 #endif // !PLATFORM(IOS)
 
         ResourceResponse resourceResponse(cfResponse.get());
-        ResourceHandle::getConnectionTimingData(parameters.connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
+        resourceResponse.setSource(ResourceResponse::Source::Network);
+#if !PLATFORM(WIN)
+        ResourceHandle::getConnectionTimingData(connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
+#endif
 
         handle->didReceiveResponse(WTFMove(resourceResponse));
     };
 
-    ProtectedParameters parameters { makeRef(*this), connection, cfResponse };
-    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
+    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveData(CFDataRef data, CFIndex originalLength)
 {
-    callOnMainThread([protectedThis = makeRef(*this), data = RetainPtr<CFDataRef>(data), originalLength = originalLength] () mutable {
+    auto work = [protectedThis = makeRef(*this), data = RetainPtr<CFDataRef>(data), originalLength = originalLength] () mutable {
         auto& handle = protectedThis->m_handle;
-        if (!protectedThis->hasHandle() || !handle->client())
+        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection())
             return;
         
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveData(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
         handle->client()->didReceiveBuffer(handle, SharedBuffer::create(data.get()), originalLength);
-    });
+    };
+    
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFinishLoading()
 {
-    callOnMainThread([protectedThis = makeRef(*this)] () mutable {
+    auto work = [protectedThis = makeRef(*this)] () mutable {
         auto& handle = protectedThis->m_handle;
-        if (!protectedThis->hasHandle() || !handle->client())
+        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
+            protectedThis->m_handle->deref();
             return;
+        }
 
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFinishLoading(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
         handle->client()->didFinishLoading(handle);
-    });
+        if (protectedThis->m_messageQueue) {
+            protectedThis->m_messageQueue->kill();
+            protectedThis->m_messageQueue = nullptr;
+        }
+        protectedThis->m_handle->deref();
+    };
+    
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFail(CFErrorRef error)
 {
-    callOnMainThread([protectedThis = makeRef(*this), error = RetainPtr<CFErrorRef>(error)] () mutable {
+    auto work = [protectedThis = makeRef(*this), error = RetainPtr<CFErrorRef>(error)] () mutable {
         auto& handle = protectedThis->m_handle;
-        if (!protectedThis->hasHandle() || !handle->client())
+        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
+            protectedThis->m_handle->deref();
             return;
+        }
         
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::didFail(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
         handle->client()->didFail(handle, ResourceError(error.get()));
-    });
+        if (protectedThis->m_messageQueue) {
+            protectedThis->m_messageQueue->kill();
+            protectedThis->m_messageQueue = nullptr;
+        }
+        protectedThis->m_handle->deref();
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
 }
 
 CFCachedURLResponseRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse(CFCachedURLResponseRef cachedResponse)
 {
-    struct ProtectedParameters {
-        Ref<ResourceHandleCFURLConnectionDelegateWithOperationQueue> protectedThis;
-        RetainPtr<CFCachedURLResponseRef> cachedResponse;
-    };
-    
-    auto work = [] (void* context) {
-        auto& parameters = *reinterpret_cast<ProtectedParameters*>(context);
-        auto& protectedThis = parameters.protectedThis;
+#if PLATFORM(WIN)
+    // Workaround for <rdar://problem/6300990> Caching does not respect Vary HTTP header.
+    // FIXME: WebCore cache has issues with Vary, too (bug 58797, bug 71509).
+    CFURLResponseRef wrappedResponse = CFCachedURLResponseGetWrappedResponse(cachedResponse);
+    if (CFHTTPMessageRef httpResponse = CFURLResponseGetHTTPResponse(wrappedResponse)) {
+        ASSERT(CFHTTPMessageIsHeaderComplete(httpResponse));
+        RetainPtr<CFStringRef> varyValue = adoptCF(CFHTTPMessageCopyHeaderFieldValue(httpResponse, CFSTR("Vary")));
+        if (varyValue)
+            return nullptr;
+    }
+#endif // PLATFORM(WIN)
+
+    auto work = [protectedThis = makeRef(*this), cachedResponse = RetainPtr<CFCachedURLResponseRef>(cachedResponse)] () {
         auto& handle = protectedThis->m_handle;
         
-        if (!protectedThis->hasHandle() || !handle->client()) {
+        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
             protectedThis->continueWillCacheResponse(nullptr);
             return;
         }
 
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
-        handle->client()->willCacheResponseAsync(handle, parameters.cachedResponse.get());
+        handle->client()->willCacheResponseAsync(handle, cachedResponse.get());
     };
     
-    ProtectedParameters parameters { makeRef(*this), cachedResponse };
-    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
+    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
     return m_cachedResponseResult.leakRef();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveChallenge(CFURLAuthChallengeRef challenge)
 {
-    callOnMainThread([protectedThis = makeRef(*this), challenge = RetainPtr<CFURLAuthChallengeRef>(challenge)] () mutable {
+    auto work = [protectedThis = makeRef(*this), challenge = RetainPtr<CFURLAuthChallengeRef>(challenge)] () mutable {
         auto& handle = protectedThis->m_handle;
         if (!protectedThis->hasHandle())
             return;
@@ -257,12 +335,17 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveChalleng
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveChallenge(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
         handle->didReceiveAuthenticationChallenge(AuthenticationChallenge(challenge.get(), handle));
-    });
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didSendBodyData(CFIndex totalBytesWritten, CFIndex totalBytesExpectedToWrite)
 {
-    callOnMainThread([protectedThis = makeRef(*this), totalBytesWritten, totalBytesExpectedToWrite] () mutable {
+    auto work = [protectedThis = makeRef(*this), totalBytesWritten, totalBytesExpectedToWrite] () mutable {
         auto& handle = protectedThis->m_handle;
         if (!protectedThis->hasHandle() || !handle->client() || !handle->connection())
             return;
@@ -270,25 +353,23 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didSendBodyData(CF
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::didSendBodyData(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
         handle->client()->didSendData(handle, totalBytesWritten, totalBytesExpectedToWrite);
-    });
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
 }
 
 Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::shouldUseCredentialStorage()
 {
-    return NO;
+    return false;
 }
 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace(CFURLProtectionSpaceRef protectionSpace)
 {
-    struct ProtectedParameters {
-        Ref<ResourceHandleCFURLConnectionDelegateWithOperationQueue> protectedThis;
-        RetainPtr<CFURLProtectionSpaceRef> protectionSpace;
-    };
-    
-    auto work = [] (void* context) {
-        auto& parameters = *reinterpret_cast<ProtectedParameters*>(context);
-        auto& protectedThis = parameters.protectedThis;
+    auto work = [protectedThis = makeRef(*this), protectionSpace = RetainPtr<CFURLProtectionSpaceRef>(protectionSpace)] () mutable {
         auto& handle = protectedThis->m_handle;
         
         if (!protectedThis->hasHandle()) {
@@ -298,7 +379,7 @@ Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToPro
 
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
-        ProtectionSpace coreProtectionSpace = ProtectionSpace(parameters.protectionSpace.get());
+        ProtectionSpace coreProtectionSpace = ProtectionSpace(protectionSpace.get());
 #if PLATFORM(IOS)
         if (coreProtectionSpace.authenticationScheme() == ProtectionSpaceAuthenticationSchemeUnknown) {
             m_boolResult = false;
@@ -309,37 +390,38 @@ Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToPro
         handle->canAuthenticateAgainstProtectionSpace(coreProtectionSpace);
     };
     
-    ProtectedParameters parameters { makeRef(*this), protectionSpace };
-    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        callOnMainThread(WTFMove(work));
+    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
     return m_boolResult;
 }
+
+void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueCanAuthenticateAgainstProtectionSpace(bool canAuthenticate)
+{
+    m_boolResult = canAuthenticate;
+    m_semaphore.signal();
+}
 #endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueWillSendRequest(CFURLRequestRef request)
 {
     m_requestResult = request;
-    dispatch_semaphore_signal(m_semaphore);
+    m_semaphore.signal();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueDidReceiveResponse()
 {
-    dispatch_semaphore_signal(m_semaphore);
+    m_semaphore.signal();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueWillCacheResponse(CFCachedURLResponseRef response)
 {
     m_cachedResponseResult = response;
-    dispatch_semaphore_signal(m_semaphore);
+    m_semaphore.signal();
 }
 
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueCanAuthenticateAgainstProtectionSpace(bool canAuthenticate)
-{
-    m_boolResult = canAuthenticate;
-    dispatch_semaphore_signal(m_semaphore);
-}
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
 } // namespace WebCore
 
 #endif // USE(CFURLCONNECTION)
index bd84da3..6ad1e4f 100644 (file)
 #include "ResourceHandleCFURLConnectionDelegate.h"
 #include <CFNetwork/CFNetwork.h>
 #include <dispatch/queue.h>
-#include <dispatch/semaphore.h>
+#include <wtf/Function.h>
+#include <wtf/MessageQueue.h>
+#include <wtf/threads/BinarySemaphore.h>
 
 namespace WebCore {
 
 class ResourceHandleCFURLConnectionDelegateWithOperationQueue final : public ResourceHandleCFURLConnectionDelegate {
 public:
-    ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle*);
+    ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle*, MessageQueue<Function<void()>>*);
     virtual ~ResourceHandleCFURLConnectionDelegateWithOperationQueue();
 
 private:
@@ -55,23 +57,21 @@ private:
     void didReceiveChallenge(CFURLAuthChallengeRef) override;
     void didSendBodyData(CFIndex totalBytesWritten, CFIndex totalBytesExpectedToWrite) override;
     Boolean shouldUseCredentialStorage() override;
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    Boolean canRespondToProtectionSpace(CFURLProtectionSpaceRef) override;
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
 
     void continueWillSendRequest(CFURLRequestRef) override;
     void continueDidReceiveResponse() override;
     void continueWillCacheResponse(CFCachedURLResponseRef) override;
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+    Boolean canRespondToProtectionSpace(CFURLProtectionSpaceRef) override;
     void continueCanAuthenticateAgainstProtectionSpace(bool) override;
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
+#endif
 
-    dispatch_queue_t m_queue;
-    dispatch_semaphore_t m_semaphore;
+    BinarySemaphore m_semaphore;
+    MessageQueue<Function<void()>>* m_messageQueue { nullptr };
 
     RetainPtr<CFURLRequestRef> m_requestResult;
     RetainPtr<CFCachedURLResponseRef> m_cachedResponseResult;
-    bool m_boolResult;
+    bool m_boolResult { false };
 };
 
 } // namespace WebCore.
index 97016e3..00e3a03 100644 (file)
@@ -179,7 +179,7 @@ void ResourceRequest::doUpdatePlatformRequest()
     if (!partition.isNull() && !partition.isEmpty()) {
         CString utf8String = partition.utf8();
         RetainPtr<CFStringRef> partitionValue = adoptCF(CFStringCreateWithBytes(0, reinterpret_cast<const UInt8*>(utf8String.data()), utf8String.length(), kCFStringEncodingUTF8, false));
-        _CFURLRequestSetProtocolProperty(cfRequest, kCFURLCachePartitionKey, partitionValue.get());
+        _CFURLRequestSetProtocolProperty(cfRequest, _kCFURLCachePartitionKey, partitionValue.get());
     }
 #endif
 
@@ -291,7 +291,7 @@ void ResourceRequest::doUpdateResourceRequest()
     }
 
 #if ENABLE(CACHE_PARTITIONING)
-    RetainPtr<CFStringRef> cachePartition = adoptCF(static_cast<CFStringRef>(_CFURLRequestCopyProtocolPropertyForKey(m_cfRequest.get(), kCFURLCachePartitionKey)));
+    RetainPtr<CFStringRef> cachePartition = adoptCF(static_cast<CFStringRef>(_CFURLRequestCopyProtocolPropertyForKey(m_cfRequest.get(), _kCFURLCachePartitionKey)));
     if (cachePartition)
         m_cachePartition = cachePartition.get();
 #endif
diff --git a/Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp b/Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.cpp
deleted file mode 100644 (file)
index 205a6f3..0000000
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "SynchronousResourceHandleCFURLConnectionDelegate.h"
-
-#if USE(CFURLCONNECTION)
-
-#include "AuthenticationCF.h"
-#include "AuthenticationChallenge.h"
-#include "LoaderRunLoopCF.h"
-#include "Logging.h"
-#include "ResourceHandle.h"
-#include "ResourceHandleClient.h"
-#include "ResourceResponse.h"
-#include "SharedBuffer.h"
-#include <wtf/RetainPtr.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
-
-#if PLATFORM(COCOA)
-#include "WebCoreURLResponse.h"
-#include <pal/spi/cf/CFNetworkSPI.h>
-#endif // PLATFORM(COCOA)
-
-#if PLATFORM(IOS)
-#include "WebCoreThreadInternal.h"
-#endif // PLATFORM(IOS)
-
-#if PLATFORM(WIN)
-#include "MIMETypeRegistry.h"
-#endif // PLATFORM(WIN)
-
-namespace WebCore {
-
-SynchronousResourceHandleCFURLConnectionDelegate::SynchronousResourceHandleCFURLConnectionDelegate(ResourceHandle* handle)
-    : ResourceHandleCFURLConnectionDelegate(handle)
-{
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::setupRequest(CFMutableURLRequestRef request)
-{
-#if PLATFORM(IOS)
-    CFURLRequestSetShouldStartSynchronously(request, 1);
-#else
-    UNUSED_PARAM(request);
-#endif
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::setupConnectionScheduling(CFURLConnectionRef connection)
-{
-#if PLATFORM(WIN)
-    CFURLConnectionScheduleWithCurrentMessageQueue(connection);
-#elif PLATFORM(IOS)
-    CFURLConnectionScheduleWithRunLoop(connection, WebThreadRunLoop(), kCFRunLoopDefaultMode);
-#else
-    CFURLConnectionScheduleWithRunLoop(connection, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
-#endif
-    CFURLConnectionScheduleDownloadWithRunLoop(connection, loaderRunLoop(), kCFRunLoopDefaultMode);
-}
-
-CFURLRequestRef SynchronousResourceHandleCFURLConnectionDelegate::willSendRequest(CFURLRequestRef cfRequest, CFURLResponseRef originalRedirectResponse)
-{
-    RetainPtr<CFURLResponseRef> redirectResponse = synthesizeRedirectResponseIfNecessary(cfRequest, originalRedirectResponse);
-
-    if (!redirectResponse) {
-        CFRetain(cfRequest);
-        return cfRequest;
-    }
-
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::willSendRequest(handle=%p) (%s)", m_handle, m_handle->firstRequest().url().string().utf8().data());
-
-    ResourceRequest request = createResourceRequest(cfRequest, redirectResponse.get());
-    auto newRequest = m_handle->willSendRequest(WTFMove(request), redirectResponse.get());
-
-    if (newRequest.isNull())
-        return nullptr;
-
-    auto newCFRequest = newRequest.cfURLRequest(UpdateHTTPBody);
-
-    CFRetain(newCFRequest);
-    return newCFRequest;
-}
-
-#if !PLATFORM(COCOA)
-static void setDefaultMIMEType(CFURLResponseRef response)
-{
-    static CFStringRef defaultMIMETypeString = defaultMIMEType().createCFString().leakRef();
-    
-    CFURLResponseSetMIMEType(response, defaultMIMETypeString);
-}
-
-static void adjustMIMETypeIfNecessary(CFURLResponseRef cfResponse)
-{
-    RetainPtr<CFStringRef> result = CFURLResponseGetMIMEType(cfResponse);
-    RetainPtr<CFStringRef> originalResult = result;
-
-    if (!result) {
-        CFURLRef cfURL = CFURLResponseGetURL(cfResponse);
-        URL url(cfURL);
-        if (url.isLocalFile()) {
-            String mimeType = mimeTypeFromURL(url);
-            result = mimeType.createCFString().leakRef();
-        }
-    }
-
-    if (!result) {
-        static CFStringRef defaultMIMETypeString = WebCore::defaultMIMEType().createCFString().leakRef();
-        result = defaultMIMETypeString;
-    }
-
-    if (result != originalResult)
-        CFURLResponseSetMIMEType(cfResponse, result.get());
-}
-#endif // !PLATFORM(COCOA)
-
-void SynchronousResourceHandleCFURLConnectionDelegate::didReceiveResponse(CFURLConnectionRef connection, CFURLResponseRef cfResponse)
-{
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::didReceiveResponse(handle=%p) (%s)", m_handle, m_handle->firstRequest().url().string().utf8().data());
-
-    if (!m_handle->client())
-        return;
-
-#if PLATFORM(COCOA)
-    // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
-    auto msg = CFURLResponseGetHTTPResponse(cfResponse);
-    int statusCode = msg ? CFHTTPMessageGetResponseStatusCode(msg) : 0;
-
-    if (statusCode != 304) {
-        bool isMainResourceLoad = m_handle->firstRequest().requester() == ResourceRequest::Requester::Main;
-        adjustMIMETypeIfNecessary(cfResponse, isMainResourceLoad);
-    }
-
-#if !PLATFORM(IOS)
-    if (_CFURLRequestCopyProtocolPropertyForKey(m_handle->firstRequest().cfURLRequest(DoNotUpdateHTTPBody), CFSTR("ForceHTMLMIMEType")))
-        CFURLResponseSetMIMEType(cfResponse, CFSTR("text/html"));
-#endif // !PLATFORM(IOS)
-#else
-    if (!CFURLResponseGetMIMEType(cfResponse))
-        adjustMIMETypeIfNecessary(cfResponse);
-
-    if (!CFURLResponseGetMIMEType(cfResponse)) {
-        // We should never be applying the default MIMEType if we told the networking layer to do content sniffing for handle.
-        ASSERT(!m_handle->shouldContentSniff());
-        setDefaultMIMEType(cfResponse);
-    }
-#endif
-
-    ResourceResponse resourceResponse(cfResponse);
-#if PLATFORM(COCOA)
-    ResourceHandle::getConnectionTimingData(connection, resourceResponse.deprecatedNetworkLoadMetrics());
-#else
-    UNUSED_PARAM(connection);
-#endif
-
-    m_handle->client()->didReceiveResponse(m_handle, WTFMove(resourceResponse));
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::didReceiveData(CFDataRef data, CFIndex originalLength)
-{
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::didReceiveData(handle=%p, bytes=%ld) (%s)", m_handle, CFDataGetLength(data), m_handle->firstRequest().url().string().utf8().data());
-
-    if (ResourceHandleClient* client = m_handle->client())
-        client->didReceiveBuffer(m_handle, SharedBuffer::create(data), originalLength);
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::didFinishLoading()
-{
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::didFinishLoading(handle=%p) (%s)", m_handle, m_handle->firstRequest().url().string().utf8().data());
-
-    if (ResourceHandleClient* client = m_handle->client())
-        client->didFinishLoading(m_handle);
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::didFail(CFErrorRef error)
-{
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::didFail(handle=%p, error = %p) (%s)", m_handle, error, m_handle->firstRequest().url().string().utf8().data());
-
-    if (ResourceHandleClient* client = m_handle->client())
-        client->didFail(m_handle, ResourceError(error));
-}
-
-CFCachedURLResponseRef SynchronousResourceHandleCFURLConnectionDelegate::willCacheResponse(CFCachedURLResponseRef cachedResponse)
-{
-#if PLATFORM(WIN)
-    // Workaround for <rdar://problem/6300990> Caching does not respect Vary HTTP header.
-    // FIXME: WebCore cache has issues with Vary, too (bug 58797, bug 71509).
-    CFURLResponseRef wrappedResponse = CFCachedURLResponseGetWrappedResponse(cachedResponse);
-    if (CFHTTPMessageRef httpResponse = CFURLResponseGetHTTPResponse(wrappedResponse)) {
-        ASSERT(CFHTTPMessageIsHeaderComplete(httpResponse));
-        RetainPtr<CFStringRef> varyValue = adoptCF(CFHTTPMessageCopyHeaderFieldValue(httpResponse, CFSTR("Vary")));
-        if (varyValue)
-            return 0;
-    }
-#endif // PLATFORM(WIN)
-
-#if PLATFORM(WIN)
-    if (m_handle->client() && !m_handle->client()->shouldCacheResponse(m_handle, cachedResponse))
-        return 0;
-#else
-    CFCachedURLResponseRef newResponse = m_handle->client()->willCacheResponse(m_handle, cachedResponse);
-    if (newResponse != cachedResponse)
-        return newResponse;
-#endif
-
-    CFRetain(cachedResponse);
-    return cachedResponse;
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::didReceiveChallenge(CFURLAuthChallengeRef challenge)
-{
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::didReceiveChallenge(handle=%p (%s)", m_handle, m_handle->firstRequest().url().string().utf8().data());
-
-    m_handle->didReceiveAuthenticationChallenge(AuthenticationChallenge(challenge, m_handle));
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::didSendBodyData(CFIndex totalBytesWritten, CFIndex totalBytesExpectedToWrite)
-{
-    if (!m_handle || !m_handle->client())
-        return;
-    m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
-}
-
-Boolean SynchronousResourceHandleCFURLConnectionDelegate::shouldUseCredentialStorage()
-{
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::shouldUseCredentialStorage(handle=%p) (%s)", m_handle, m_handle->firstRequest().url().string().utf8().data());
-
-    if (!m_handle)
-        return false;
-
-    return m_handle->shouldUseCredentialStorage();
-}
-
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-Boolean SynchronousResourceHandleCFURLConnectionDelegate::canRespondToProtectionSpace(CFURLProtectionSpaceRef protectionSpace)
-{
-    ASSERT(m_handle);
-
-    LOG(Network, "CFNet - SynchronousResourceHandleCFURLConnectionDelegate::canRespondToProtectionSpace(handle=%p (%s)", m_handle, m_handle->firstRequest().url().string().utf8().data());
-
-    ProtectionSpace coreProtectionSpace = ProtectionSpace(protectionSpace);
-#if PLATFORM(IOS)
-    if (coreProtectionSpace.authenticationScheme() == ProtectionSpaceAuthenticationSchemeUnknown)
-        return false;
-    return m_handle->canAuthenticateAgainstProtectionSpace(coreProtectionSpace);
-#else
-    return m_handle->canAuthenticateAgainstProtectionSpace(coreProtectionSpace);
-#endif
-}
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
-
-void SynchronousResourceHandleCFURLConnectionDelegate::continueWillSendRequest(CFURLRequestRef)
-{
-    ASSERT_NOT_REACHED();
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::continueDidReceiveResponse()
-{
-    ASSERT_NOT_REACHED();
-}
-
-void SynchronousResourceHandleCFURLConnectionDelegate::continueWillCacheResponse(CFCachedURLResponseRef)
-{
-    ASSERT_NOT_REACHED();
-}
-
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-void SynchronousResourceHandleCFURLConnectionDelegate::continueCanAuthenticateAgainstProtectionSpace(bool)
-{
-    ASSERT_NOT_REACHED();
-}
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
-
-} // namespace WebCore.
-
-#endif
diff --git a/Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.h b/Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.h
deleted file mode 100644 (file)
index c648932..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2004-2013 Apple Inc.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#pragma once
-
-#if USE(CFURLCONNECTION)
-
-#include "ResourceHandleCFURLConnectionDelegate.h"
-
-namespace WebCore {
-
-class SynchronousResourceHandleCFURLConnectionDelegate final : public ResourceHandleCFURLConnectionDelegate {
-public:
-    SynchronousResourceHandleCFURLConnectionDelegate(ResourceHandle*);
-
-    void didReceiveData(CFDataRef, CFIndex originalLength) override;
-    void didFinishLoading() override;
-    void didFail(CFErrorRef) override;
-
-private:
-    void setupRequest(CFMutableURLRequestRef) override;
-    void setupConnectionScheduling(CFURLConnectionRef) override;
-
-    CFURLRequestRef willSendRequest(CFURLRequestRef, CFURLResponseRef) override;
-    void didReceiveResponse(CFURLConnectionRef, CFURLResponseRef) override;
-    CFCachedURLResponseRef willCacheResponse(CFCachedURLResponseRef) override;
-    void didReceiveChallenge(CFURLAuthChallengeRef) override;
-    void didSendBodyData(CFIndex totalBytesWritten, CFIndex totalBytesExpectedToWrite) override;
-    Boolean shouldUseCredentialStorage() override;
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    Boolean canRespondToProtectionSpace(CFURLProtectionSpaceRef) override;
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
-
-    void continueWillSendRequest(CFURLRequestRef) override;
-    void continueDidReceiveResponse() override;
-    void continueWillCacheResponse(CFCachedURLResponseRef) override;
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    void continueCanAuthenticateAgainstProtectionSpace(bool) override;
-#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
-};
-
-} // namespace WebCore.
-
-#endif // USE(CFURLCONNECTION)
index 1bcbd05..d550b08 100644 (file)
@@ -350,7 +350,7 @@ void MultipartHandle::didReceiveResponse()
         response.setMimeType(mimeType.convertToASCIILowercase());
         response.setTextEncodingName(extractCharsetFromMediaType(contentType));
 
-        d->client()->didReceiveResponse(m_resourceHandle, WTFMove(response));
+        m_resourceHandle->didReceiveResponse(WTFMove(response));
     }
 }
 
index ecdbf11..0afcdd0 100644 (file)
@@ -274,7 +274,6 @@ void ResourceHandle::platformContinueSynchronousDidReceiveResponse()
 void ResourceHandle::continueWillSendRequest(ResourceRequest&& request)
 {
     ASSERT(isMainThread());
-    ASSERT(!client() || client()->usesAsyncCallbacks());
 
     if (d->m_delegate)
         d->m_delegate->continueWillSendRequest(WTFMove(request));
index cc7a831..0d7d44c 100644 (file)
@@ -363,12 +363,7 @@ void ResourceHandleCurlDelegate::willSendRequest()
     }
 
     ResourceResponse responseCopy = response();
-    if (m_handle->client()->usesAsyncCallbacks())
-        m_handle->client()->willSendRequestAsync(m_handle, WTFMove(newRequest), WTFMove(responseCopy));
-    else {
-        auto request = m_handle->client()->willSendRequest(m_handle, WTFMove(newRequest), WTFMove(responseCopy));
-        continueAfterWillSendRequest(WTFMove(request));
-    }
+    m_handle->client()->willSendRequestAsync(m_handle, WTFMove(newRequest), WTFMove(responseCopy));
 }
 
 void ResourceHandleCurlDelegate::continueWillSendRequest(ResourceRequest&& request)
@@ -444,7 +439,7 @@ void ResourceHandleCurlDelegate::handleDataURL()
 
     if (base64) {
         data = decodeURLEscapeSequences(data);
-        m_handle->client()->didReceiveResponse(m_handle, WTFMove(response));
+        m_handle->didReceiveResponse(WTFMove(response));
 
         // didReceiveResponse might cause the client to be deleted.
         if (m_handle->client()) {
@@ -455,7 +450,7 @@ void ResourceHandleCurlDelegate::handleDataURL()
     } else {
         TextEncoding encoding(charset);
         data = decodeURLEscapeSequences(data, encoding);
-        m_handle->client()->didReceiveResponse(m_handle, WTFMove(response));
+        m_handle->didReceiveResponse(WTFMove(response));
 
         // didReceiveResponse might cause the client to be deleted.
         if (m_handle->client()) {
index 43e0fa1..25bc3e7 100644 (file)
 - (CFURLRef)_cfurl;
 @end
 
+#endif
+
 namespace WebCore {
 
+static NSArray *httpCookies(CFHTTPCookieStorageRef cookieStorage)
+{
+    if (!cookieStorage)
+        return [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
+    
+    auto cookies = adoptCF(CFHTTPCookieStorageCopyCookies(cookieStorage));
+    return [NSHTTPCookie _cf2nsCookies:cookies.get()];
+}
+
+static void deleteHTTPCookie(CFHTTPCookieStorageRef cookieStorage, NSHTTPCookie *cookie)
+{
+    if (!cookieStorage) {
+        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
+        return;
+    }
+    
+    CFHTTPCookieStorageDeleteCookie(cookieStorage, [cookie _GetInternalCFHTTPCookie]);
+}
+
+#if !USE(CFURLCONNECTION)
+
 static NSArray *httpCookiesForURL(CFHTTPCookieStorageRef cookieStorage, NSURL *firstParty, NSURL *url)
 {
     if (!cookieStorage)
@@ -180,15 +203,6 @@ static std::pair<String, bool> cookiesForSession(const NetworkStorageSession& se
     return { String(), false };
 }
 
-static NSArray *httpCookies(CFHTTPCookieStorageRef cookieStorage)
-{
-    if (!cookieStorage)
-        return [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
-
-    auto cookies = adoptCF(CFHTTPCookieStorageCopyCookies(cookieStorage));
-    return [NSHTTPCookie _cf2nsCookies:cookies.get()];
-}
-
 static void setHTTPCookiesForURL(CFHTTPCookieStorageRef cookieStorage, NSArray *cookies, NSURL *url, NSURL *mainDocumentURL)
 {
     if (!cookieStorage) {
@@ -200,16 +214,6 @@ static void setHTTPCookiesForURL(CFHTTPCookieStorageRef cookieStorage, NSArray *
     CFHTTPCookieStorageSetCookies(cookieStorage, cfCookies.get(), [url _cfurl], [mainDocumentURL _cfurl]);
 }
 
-static void deleteHTTPCookie(CFHTTPCookieStorageRef cookieStorage, NSHTTPCookie *cookie)
-{
-    if (!cookieStorage) {
-        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
-        return;
-    }
-
-    CFHTTPCookieStorageDeleteCookie(cookieStorage, [cookie _GetInternalCFHTTPCookie]);
-}
-
 static void deleteAllHTTPCookies(CFHTTPCookieStorageRef cookieStorage)
 {
     if (!cookieStorage) {
@@ -344,12 +348,8 @@ void deleteAllCookies(const NetworkStorageSession& session)
     deleteAllHTTPCookies(session.cookieStorage().get());
 }
 
-}
-
 #endif // !USE(CFURLCONNECTION)
 
-namespace WebCore {
-
 void deleteCookiesForHostnames(const NetworkStorageSession& session, const Vector<String>& hostnames)
 {
     BEGIN_BLOCK_OBJC_EXCEPTIONS;
index 3940dbe..06826f1 100644 (file)
@@ -44,7 +44,6 @@
 #import "SharedBuffer.h"
 #import "SubresourceLoader.h"
 #import "SynchronousLoaderClient.h"
-#import "WebCoreResourceHandleAsDelegate.h"
 #import "WebCoreResourceHandleAsOperationQueueDelegate.h"
 #import "WebCoreURLResponse.h"
 #import <pal/spi/cf/CFNetworkSPI.h>
@@ -248,48 +247,21 @@ bool ResourceHandle::start()
 
 #if !PLATFORM(IOS)
     createNSURLConnection(
-        ResourceHandle::makeDelegate(shouldUseCredentialStorage),
+        ResourceHandle::makeDelegate(shouldUseCredentialStorage, nullptr),
         shouldUseCredentialStorage,
         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
         schedulingBehavior);
 #else
     createNSURLConnection(
-        ResourceHandle::makeDelegate(shouldUseCredentialStorage),
+        ResourceHandle::makeDelegate(shouldUseCredentialStorage, nullptr),
         shouldUseCredentialStorage,
         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
         schedulingBehavior,
         (NSDictionary *)client()->connectionProperties(this).get());
 #endif
 
-    bool scheduled = false;
-    if (SchedulePairHashSet* scheduledPairs = d->m_context->scheduledRunLoopPairs()) {
-        SchedulePairHashSet::iterator end = scheduledPairs->end();
-        for (SchedulePairHashSet::iterator it = scheduledPairs->begin(); it != end; ++it) {
-            if (NSRunLoop *runLoop = (*it)->nsRunLoop()) {
-                [connection() scheduleInRunLoop:runLoop forMode:(NSString *)(*it)->mode()];
-                scheduled = true;
-            }
-        }
-    }
-
-    if (d->m_usesAsyncCallbacks) {
-        ASSERT(!scheduled);
-        [connection() setDelegateQueue:operationQueueForAsyncClients()];
-        scheduled = true;
-    }
-#if PLATFORM(IOS)
-    else {
-        [connection() scheduleInRunLoop:WebThreadNSRunLoop() forMode:NSDefaultRunLoopMode];
-        scheduled = true;
-    }
-#endif
-
-    // Start the connection if we did schedule with at least one runloop.
-    // We can't start the connection until we have one runloop scheduled.
-    if (scheduled)
-        [connection() start];
-    else
-        d->m_startWhenScheduled = true;
+    [connection() setDelegateQueue:operationQueueForAsyncClients()];
+    [connection() start];
 
     LOG(Network, "Handle %p starting connection %p for %@", this, connection(), firstRequest().nsURLRequest(DoNotUpdateHTTPBody));
     
@@ -330,10 +302,6 @@ void ResourceHandle::schedule(SchedulePair& pair)
     if (!runLoop)
         return;
     [d->m_connection.get() scheduleInRunLoop:runLoop forMode:(NSString *)pair.mode()];
-    if (d->m_startWhenScheduled) {
-        [d->m_connection.get() start];
-        d->m_startWhenScheduled = false;
-    }
 }
 
 void ResourceHandle::unschedule(SchedulePair& pair)
@@ -344,18 +312,15 @@ void ResourceHandle::unschedule(SchedulePair& pair)
 
 #endif
 
-id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage)
+id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage, MessageQueue<Function<void()>>* queue)
 {
     ASSERT(!d->m_delegate);
 
     id <NSURLConnectionDelegate> delegate;
-    if (d->m_usesAsyncCallbacks) {
-        if (shouldUseCredentialStorage)
-            delegate = [[WebCoreResourceHandleAsOperationQueueDelegate alloc] initWithHandle:this];
-        else
-            delegate = [[WebCoreResourceHandleWithCredentialStorageAsOperationQueueDelegate alloc] initWithHandle:this];
-    } else
-        delegate = [[WebCoreResourceHandleAsDelegate alloc] initWithHandle:this];
+    if (shouldUseCredentialStorage)
+        delegate = [[WebCoreResourceHandleAsOperationQueueDelegate alloc] initWithHandle:this messageQueue:queue];
+    else
+        delegate = [[WebCoreResourceHandleWithCredentialStorageAsOperationQueueDelegate alloc] initWithHandle:this messageQueue:queue];
 
     d->m_delegate = delegate;
     [delegate release];
@@ -366,7 +331,7 @@ id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage)
 id ResourceHandle::delegate()
 {
     if (!d->m_delegate)
-        return makeDelegate(false);
+        return makeDelegate(false, nullptr);
     return d->m_delegate.get();
 }
 
@@ -409,24 +374,26 @@ void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* contex
     bool shouldUseCredentialStorage = storedCredentialsPolicy == StoredCredentialsPolicy::Use;
 #if !PLATFORM(IOS)
     handle->createNSURLConnection(
-        handle->makeDelegate(shouldUseCredentialStorage),
+        handle->makeDelegate(shouldUseCredentialStorage, &client.messageQueue()),
         shouldUseCredentialStorage,
         handle->shouldContentSniff() || context->localFileContentSniffingEnabled(),
         SchedulingBehavior::Synchronous);
 #else
     handle->createNSURLConnection(
-        handle->makeDelegate(shouldUseCredentialStorage), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
+        handle->makeDelegate(shouldUseCredentialStorage, &client.messageQueue()), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
         shouldUseCredentialStorage,
         handle->shouldContentSniff() || (context && context->localFileContentSniffingEnabled()),
         SchedulingBehavior::Synchronous,
         (NSDictionary *)handle->client()->connectionProperties(handle.get()).get());
 #endif
 
-    [handle->connection() scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(NSString *)synchronousLoadRunLoopMode()];
+    [handle->connection() setDelegateQueue:operationQueueForAsyncClients()];
     [handle->connection() start];
     
-    while (!client.isDone())
-        [[NSRunLoop currentRunLoop] runMode:(NSString *)synchronousLoadRunLoopMode() beforeDate:[NSDate distantFuture]];
+    do {
+        if (auto task = client.messageQueue().waitForMessage())
+            (*task)();
+    } while (!client.messageQueue().killed());
 
     error = client.error();
     
@@ -486,24 +453,12 @@ ResourceRequest ResourceHandle::willSendRequest(ResourceRequest&& request, Resou
         }
     }
 
-    if (d->m_usesAsyncCallbacks) {
-        client()->willSendRequestAsync(this, WTFMove(request), WTFMove(redirectResponse));
-        return { };
-    }
-
-    Ref<ResourceHandle> protectedThis(*this);
-    auto newRequest = client()->willSendRequest(this, WTFMove(request), WTFMove(redirectResponse));
-
-    // Client call may not preserve the session, especially if the request is sent over IPC.
-    if (!newRequest.isNull())
-        newRequest.setStorageSession(d->m_storageSession.get());
-    return newRequest;
+    client()->willSendRequestAsync(this, WTFMove(request), WTFMove(redirectResponse));
+    return { };
 }
 
 void ResourceHandle::continueWillSendRequest(ResourceRequest&& newRequest)
 {
-    ASSERT(d->m_usesAsyncCallbacks);
-
     // Client call may not preserve the session, especially if the request is sent over IPC.
     if (!newRequest.isNull())
         newRequest.setStorageSession(d->m_storageSession.get());
@@ -512,17 +467,9 @@ void ResourceHandle::continueWillSendRequest(ResourceRequest&& newRequest)
 
 void ResourceHandle::continueDidReceiveResponse()
 {
-    ASSERT(d->m_usesAsyncCallbacks);
-
     [delegate() continueDidReceiveResponse];
 }
 
-bool ResourceHandle::shouldUseCredentialStorage()
-{
-    ASSERT(!d->m_usesAsyncCallbacks);
-    return client() && client()->shouldUseCredentialStorage(this);
-}
-
 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
 {
     ASSERT(!d->m_currentMacChallenge);
@@ -618,22 +565,15 @@ bool ResourceHandle::tryHandlePasswordBasedAuthentication(const AuthenticationCh
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
 {
-    ResourceHandleClient* client = this->client();
-    if (d->m_usesAsyncCallbacks) {
-        if (client)
-            client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
-        else
-            continueCanAuthenticateAgainstProtectionSpace(false);
-        return false; // Ignored by caller.
-    }
-
-    return client && client->canAuthenticateAgainstProtectionSpace(this, protectionSpace);
+    if (ResourceHandleClient* client = this->client())
+        client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
+    else
+        continueCanAuthenticateAgainstProtectionSpace(false);
+    return false; // Ignored by caller.
 }
 
 void ResourceHandle::continueCanAuthenticateAgainstProtectionSpace(bool result)
 {
-    ASSERT(d->m_usesAsyncCallbacks);
-
     [(id)delegate() continueCanAuthenticateAgainstProtectionSpace:result];
 }
 #endif
@@ -719,8 +659,6 @@ void ResourceHandle::receivedChallengeRejection(const AuthenticationChallenge& c
 
 void ResourceHandle::continueWillCacheResponse(NSCachedURLResponse *response)
 {
-    ASSERT(d->m_usesAsyncCallbacks);
-
     [(id)delegate() continueWillCacheResponse:response];
 }
 
diff --git a/Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.h b/Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.h
deleted file mode 100644 (file)
index a873b48..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#pragma once
-
-namespace WebCore {
-class ResourceHandle;
-}
-
-@protocol WebCoreResourceLoaderDelegate
-- (void)detachHandle;
-@end
-
-#if !USE(CFURLCONNECTION)
-
-@interface WebCoreResourceHandleAsDelegate : NSObject <NSURLConnectionDelegate, WebCoreResourceLoaderDelegate> {
-    WebCore::ResourceHandle* m_handle;
-}
-- (id)initWithHandle:(WebCore::ResourceHandle*)handle;
-@end
-
-#endif // !USE(CFURLCONNECTION)
diff --git a/Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.mm b/Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.mm
deleted file mode 100644 (file)
index 4c2a4fa..0000000
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "WebCoreResourceHandleAsDelegate.h"
-
-#if !USE(CFURLCONNECTION)
-
-#import "AuthenticationChallenge.h"
-#import "AuthenticationMac.h"
-#import "Logging.h"
-#import "ResourceHandle.h"
-#import "ResourceHandleClient.h"
-#import "ResourceRequest.h"
-#import "ResourceResponse.h"
-#import "SharedBuffer.h"
-#import "WebCoreURLResponse.h"
-#import <pal/spi/cf/CFNetworkSPI.h>
-
-using namespace WebCore;
-
-@implementation WebCoreResourceHandleAsDelegate
-
-- (id)initWithHandle:(ResourceHandle*)handle
-{
-    self = [self init];
-    if (!self)
-        return nil;
-    m_handle = handle;
-    return self;
-}
-
-- (void)detachHandle
-{
-    m_handle = nullptr;
-}
-
-- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)newRequest redirectResponse:(NSURLResponse *)redirectResponse
-{
-    UNUSED_PARAM(connection);
-
-    if (!m_handle)
-        return nil;
-
-    redirectResponse = synthesizeRedirectResponseIfNecessary([connection currentRequest], newRequest, redirectResponse);
-    
-    // See <rdar://problem/5380697>. This is a workaround for a behavior change in CFNetwork where willSendRequest gets called more often.
-    if (!redirectResponse)
-        return newRequest;
-
-#if !LOG_DISABLED
-    if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]])
-        LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:%d, Location:<%@>", m_handle, connection, [newRequest description], static_cast<int>([(id)redirectResponse statusCode]), [[(id)redirectResponse allHeaderFields] objectForKey:@"Location"]);
-    else
-        LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]); 
-#endif
-
-    return m_handle->willSendRequest(newRequest, redirectResponse).nsURLRequest(UpdateHTTPBody);
-}
-
-- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
-{
-    UNUSED_PARAM(connection);
-
-    LOG(Network, "Handle %p delegate connectionShouldUseCredentialStorage:%p", m_handle, connection);
-
-#if PLATFORM(IOS)
-    return NO;
-#else
-    if (!m_handle)
-        return NO;
-
-    return m_handle->shouldUseCredentialStorage();
-#endif
-}
-
-- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
-{
-    UNUSED_PARAM(connection);
-
-    LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
-
-    if (!m_handle) {
-        [[challenge sender] cancelAuthenticationChallenge:challenge];
-        return;
-    }
-    m_handle->didReceiveAuthenticationChallenge(core(challenge));
-}
-
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
-{
-    UNUSED_PARAM(connection);
-
-    LOG(Network, "Handle %p delegate connection:%p canAuthenticateAgainstProtectionSpace:%@://%@:%u realm:%@ method:%@ %@%@", m_handle, connection, [protectionSpace protocol], [protectionSpace host], [protectionSpace port], [protectionSpace realm], [protectionSpace authenticationMethod], [protectionSpace isProxy] ? @"proxy:" : @"", [protectionSpace isProxy] ? [protectionSpace proxyType] : @"");
-
-    if (!m_handle)
-        return NO;
-
-    return m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace));
-}
-#endif
-
-- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
-{
-    LOG(Network, "Handle %p delegate connection:%p didReceiveResponse:%p (HTTP status %d, reported MIMEType '%s')", m_handle, connection, response, [response respondsToSelector:@selector(statusCode)] ? [(id)response statusCode] : 0, [[response MIMEType] UTF8String]);
-
-    if (!m_handle || !m_handle->client())
-        return;
-
-    // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
-    int statusCode = [response respondsToSelector:@selector(statusCode)] ? [(id)response statusCode] : 0;
-    if (statusCode != 304) {
-        bool isMainResourceLoad = m_handle->firstRequest().requester() == ResourceRequest::Requester::Main;
-        adjustMIMETypeIfNecessary([response _CFURLResponse], isMainResourceLoad);
-    }
-
-#if !PLATFORM(IOS)
-    if ([m_handle->firstRequest().nsURLRequest(DoNotUpdateHTTPBody) _propertyForKey:@"ForceHTMLMIMEType"])
-        [response _setMIMEType:@"text/html"];
-#endif
-
-    ResourceResponse resourceResponse(response);
-    resourceResponse.setSource(ResourceResponse::Source::Network);
-    ResourceHandle::getConnectionTimingData(connection, resourceResponse.deprecatedNetworkLoadMetrics());
-
-    m_handle->didReceiveResponse(WTFMove(resourceResponse));
-}
-
-- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data lengthReceived:(long long)lengthReceived
-{
-    UNUSED_PARAM(connection);
-    UNUSED_PARAM(lengthReceived);
-
-    LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
-
-#if PLATFORM(IOS)
-    if ([data length] == 0) // <rdar://problem/5532931>
-        return;
-#endif
-
-    if (!m_handle || !m_handle->client())
-        return;
-    // FIXME: If we get more than 2B bytes in a single chunk, this code won't do the right thing.
-    // However, with today's computers and networking speeds, this won't happen in practice.
-    // Could be an issue with a giant local file.
-
-    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
-    // -1 means we do not provide any data about transfer size to inspector so it would use
-    // Content-Length headers or content size to show transfer size.
-    m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(data), -1);
-}
-
-- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
-{
-    UNUSED_PARAM(connection);
-    UNUSED_PARAM(bytesWritten);
-
-    LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
-
-    if (!m_handle || !m_handle->client())
-        return;
-    m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
-}
-
-- (void)connectionDidFinishLoading:(NSURLConnection *)connection
-{
-    UNUSED_PARAM(connection);
-
-    LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
-
-    if (!m_handle || !m_handle->client())
-        return;
-
-    m_handle->client()->didFinishLoading(m_handle);
-}
-
-- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-{
-    UNUSED_PARAM(connection);
-
-    LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
-
-    if (!m_handle || !m_handle->client())
-        return;
-
-    m_handle->client()->didFail(m_handle, error);
-}
-
-
-- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
-{
-    LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
-
-    UNUSED_PARAM(connection);
-
-    if (!m_handle || !m_handle->client())
-        return nil;
-
-    return m_handle->client()->willCacheResponse(m_handle, cachedResponse);
-}
-
-@end
-
-#endif // !USE(CFURLCONNECTION)
-
index 03fc6e9..26a793b 100644 (file)
 
 #if !USE(CFURLCONNECTION)
 
-#include "WebCoreResourceHandleAsDelegate.h"
 #include <dispatch/dispatch.h>
+#include <wtf/Function.h>
+#include <wtf/MessageQueue.h>
 #include <wtf/RetainPtr.h>
 
 namespace WebCore {
 class ResourceHandle;
 }
 
-@interface WebCoreResourceHandleAsOperationQueueDelegate : NSObject <NSURLConnectionDelegate, WebCoreResourceLoaderDelegate> {
+@interface WebCoreResourceHandleAsOperationQueueDelegate : NSObject <NSURLConnectionDelegate> {
     WebCore::ResourceHandle* m_handle;
 
     // Synchronous delegates on operation queue wait until main thread sends an asynchronous response.
     dispatch_semaphore_t m_semaphore;
+    MessageQueue<Function<void()>>* m_messageQueue;
     RetainPtr<NSURLRequest> m_requestResult;
     RetainPtr<NSCachedURLResponse> m_cachedResponseResult;
     BOOL m_boolResult;
 }
 
-- (id)initWithHandle:(WebCore::ResourceHandle*)handle;
+- (void)detachHandle;
+- (id)initWithHandle:(WebCore::ResourceHandle*)handle messageQueue:(MessageQueue<Function<void()>>*)messageQueue;
 - (void)continueWillSendRequest:(NSURLRequest *)newRequest;
 - (void)continueDidReceiveResponse;
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 - (void)continueCanAuthenticateAgainstProtectionSpace:(BOOL)canAuthenticate;
-#endif
 - (void)continueWillCacheResponse:(NSCachedURLResponse *)response;
 @end
 
index 9651bae..04370d8 100644 (file)
@@ -36,6 +36,7 @@
 #import "ResourceRequest.h"
 #import "ResourceResponse.h"
 #import "SharedBuffer.h"
+#import "SynchronousLoaderClient.h"
 #import "WebCoreURLResponse.h"
 #import <pal/spi/cf/CFNetworkSPI.h>
 #import <wtf/MainThread.h>
@@ -44,7 +45,7 @@ using namespace WebCore;
 
 @implementation WebCoreResourceHandleAsOperationQueueDelegate
 
-- (id)initWithHandle:(ResourceHandle*)handle
+- (id)initWithHandle:(ResourceHandle*)handle messageQueue:(MessageQueue<Function<void()>>*)messageQueue
 {
     self = [self init];
     if (!self)
@@ -52,6 +53,7 @@ using namespace WebCore;
 
     m_handle = handle;
     m_semaphore = dispatch_semaphore_create(0);
+    m_messageQueue = messageQueue;
 
     return self;
 }
@@ -113,17 +115,21 @@ using namespace WebCore;
         LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]); 
 #endif
 
-    RetainPtr<id> protector(self);
-
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), newRequest = RetainPtr<NSURLRequest>(newRequest), redirectResponse = RetainPtr<NSURLResponse>(redirectResponse)] () mutable {
         if (!m_handle) {
             m_requestResult = nullptr;
             dispatch_semaphore_signal(m_semaphore);
             return;
         }
 
-        m_handle->willSendRequest(newRequest, redirectResponse);
-    });
+        m_handle->willSendRequest(newRequest.get(), redirectResponse.get());
+    };
+
+    
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
 
     dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     return m_requestResult.autorelease();
@@ -136,16 +142,20 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self, protectedSelf = RetainPtr<id>(self), challenge = RetainPtr<NSURLAuthenticationChallenge>(challenge)] () mutable {
         if (!m_handle) {
-            [[challenge sender] cancelAuthenticationChallenge:challenge];
+            [[challenge sender] cancelAuthenticationChallenge:challenge.get()];
             return;
         }
-        m_handle->didReceiveAuthenticationChallenge(core(challenge));
-    });
+        m_handle->didReceiveAuthenticationChallenge(core(challenge.get()));
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
 }
 
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
 {
     ASSERT(!isMainThread());
@@ -153,21 +163,23 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p canAuthenticateAgainstProtectionSpace:%@://%@:%u realm:%@ method:%@ %@%@", m_handle, connection, [protectionSpace protocol], [protectionSpace host], [protectionSpace port], [protectionSpace realm], [protectionSpace authenticationMethod], [protectionSpace isProxy] ? @"proxy:" : @"", [protectionSpace isProxy] ? [protectionSpace proxyType] : @"");
 
-    RetainPtr<id> protector(self);
-
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), protectionSpace = RetainPtr<NSURLProtectionSpace>(protectionSpace)] () mutable {
         if (!m_handle) {
             m_boolResult = NO;
             dispatch_semaphore_signal(m_semaphore);
             return;
         }
-        m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace));
-    });
+        m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace.get()));
+    };
 
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
+    
     dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     return m_boolResult;
 }
-#endif
 
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)r
 {
@@ -175,9 +187,8 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didReceiveResponse:%p (HTTP status %d, reported MIMEType '%s')", m_handle, connection, r, [r respondsToSelector:@selector(statusCode)] ? [(id)r statusCode] : 0, [[r MIMEType] UTF8String]);
 
-    RetainPtr<id> protector(self);
-
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), r = RetainPtr<NSURLResponse>(r), connection = RetainPtr<NSURLConnection>(connection)] () mutable {
+        RefPtr<ResourceHandle> protectedHandle(m_handle);
         if (!m_handle || !m_handle->client()) {
             dispatch_semaphore_signal(m_semaphore);
             return;
@@ -193,12 +204,18 @@ using namespace WebCore;
         if ([m_handle->firstRequest().nsURLRequest(DoNotUpdateHTTPBody) _propertyForKey:@"ForceHTMLMIMEType"])
             [r _setMIMEType:@"text/html"];
 
-        ResourceResponse resourceResponse(r);
-        ResourceHandle::getConnectionTimingData(connection, resourceResponse.deprecatedNetworkLoadMetrics());
+        ResourceResponse resourceResponse(r.get());
+        resourceResponse.setSource(ResourceResponse::Source::Network);
+        ResourceHandle::getConnectionTimingData(connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
 
         m_handle->didReceiveResponse(WTFMove(resourceResponse));
-    });
+    };
 
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
+    
     dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
 }
 
@@ -210,7 +227,7 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), data = RetainPtr<NSData>(data)] () mutable {
         if (!m_handle || !m_handle->client())
             return;
         // FIXME: If we get more than 2B bytes in a single chunk, this code won't do the right thing.
@@ -220,8 +237,13 @@ using namespace WebCore;
         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
         // -1 means we do not provide any data about transfer size to inspector so it would use
         // Content-Length headers or content size to show transfer size.
-        m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(data), -1);
-    });
+        m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(data.get()), -1);
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
 }
 
 - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
@@ -232,11 +254,16 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), totalBytesWritten = totalBytesWritten, totalBytesExpectedToWrite = totalBytesExpectedToWrite] () mutable {
         if (!m_handle || !m_handle->client())
             return;
         m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
-    });
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
 }
 
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
@@ -246,12 +273,21 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto task = [self = self, protectedSelf = RetainPtr<id>(self)] () mutable {
         if (!m_handle || !m_handle->client())
             return;
 
         m_handle->client()->didFinishLoading(m_handle);
-    });
+        if (m_messageQueue) {
+            m_messageQueue->kill();
+            m_messageQueue = nullptr;
+        }
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(task)));
+    else
+        dispatch_async(dispatch_get_main_queue(), task);
 }
 
 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
@@ -261,12 +297,21 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), error = RetainPtr<NSError>(error)] () mutable {
         if (!m_handle || !m_handle->client())
             return;
 
-        m_handle->client()->didFail(m_handle, error);
-    });
+        m_handle->client()->didFail(m_handle, error.get());
+        if (m_messageQueue) {
+            m_messageQueue->kill();
+            m_messageQueue = nullptr;
+        }
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
 }
 
 
@@ -277,17 +322,20 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
 
-    RetainPtr<id> protector(self);
-
-    dispatch_async(dispatch_get_main_queue(), ^{
+    auto work = [self = self, protectedSelf = RetainPtr<id>(self), cachedResponse = RetainPtr<NSCachedURLResponse>(cachedResponse)] () mutable {
         if (!m_handle || !m_handle->client()) {
             m_cachedResponseResult = nullptr;
             dispatch_semaphore_signal(m_semaphore);
             return;
         }
 
-        m_handle->client()->willCacheResponseAsync(m_handle, cachedResponse);
-    });
+        m_handle->client()->willCacheResponseAsync(m_handle, cachedResponse.get());
+    };
+
+    if (m_messageQueue)
+        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
+    else
+        dispatch_async(dispatch_get_main_queue(), work);
 
     dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     return m_cachedResponseResult.autorelease();
index 7499972..348870d 100644 (file)
@@ -353,13 +353,7 @@ static void doRedirect(ResourceHandle* handle)
     cleanupSoupRequestOperation(handle);
 
     ResourceResponse responseCopy = d->m_response;
-    if (d->client()->usesAsyncCallbacks())
-        d->client()->willSendRequestAsync(handle, WTFMove(newRequest), WTFMove(responseCopy));
-    else {
-        auto request = d->client()->willSendRequest(handle, WTFMove(newRequest), WTFMove(responseCopy));
-        continueAfterWillSendRequest(handle, WTFMove(request));
-    }
-
+    d->client()->willSendRequestAsync(handle, WTFMove(newRequest), WTFMove(responseCopy));
 }
 
 static void redirectSkipCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
@@ -1032,13 +1026,11 @@ static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
 
 void ResourceHandle::continueWillSendRequest(ResourceRequest&& request)
 {
-    ASSERT(!client() || client()->usesAsyncCallbacks());
     continueAfterWillSendRequest(this, WTFMove(request));
 }
 
 void ResourceHandle::continueDidReceiveResponse()
 {
-    ASSERT(!client() || client()->usesAsyncCallbacks());
     continueAfterDidReceiveResponse(this);
 }
 
index c6ff15a..a196dff 100644 (file)
@@ -71,6 +71,18 @@ void BlobDownloadClient::didDecideDownloadDestination(const String& destinationP
     m_download.continueDidReceiveResponse();
 }
 
+void BlobDownloadClient::willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&)
+{
+    ASSERT_NOT_REACHED();
+}
+
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+void BlobDownloadClient::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&)
+{
+    ASSERT_NOT_REACHED();
+}
+#endif
+
 void BlobDownloadClient::didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&& buffer, int)
 {
     writeToFile(m_destinationFile, buffer->data(), buffer->size());
index 4a42cc2..1b441f6 100644 (file)
@@ -49,7 +49,10 @@ private:
     void didReceiveBuffer(WebCore::ResourceHandle*, Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) final;
     void didFinishLoading(WebCore::ResourceHandle*) final;
     void didFail(WebCore::ResourceHandle*, const WebCore::ResourceError&) final;
-    bool usesAsyncCallbacks() final { return true; }
+    void willSendRequestAsync(WebCore::ResourceHandle*, WebCore::ResourceRequest&&, WebCore::ResourceResponse&&) final;
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
+    void canAuthenticateAgainstProtectionSpaceAsync(WebCore::ResourceHandle*, const WebCore::ProtectionSpace&) final;
+#endif
 
     Download& m_download;
     String m_destinationPath;
index 46f4e41..11dc42e 100644 (file)
@@ -251,7 +251,7 @@ void NetworkConnectionToWebProcess::loadPing(NetworkResourceLoadParameters&& loa
     auto context = RemoteNetworkingContext::create(loadParameters.sessionID, loadParameters.shouldClearReferrerOnHTTPSToHTTPRedirect);
 
     // PingHandle manages its own lifetime, deleting itself when its purpose has been fulfilled.
-    new PingHandle(context.ptr(), loadParameters.request, loadParameters.storedCredentialsPolicy == StoredCredentialsPolicy::Use, PingHandle::UsesAsyncCallbacks::Yes, loadParameters.shouldFollowRedirects, WTFMove(completionHandler));
+    new PingHandle(context.ptr(), loadParameters.request, loadParameters.storedCredentialsPolicy == StoredCredentialsPolicy::Use, loadParameters.shouldFollowRedirects, WTFMove(completionHandler));
 #endif
 }
 
index 36ae929..9d53179 100644 (file)
@@ -127,7 +127,6 @@ private:
     bool shouldUseCredentialStorage(WebCore::ResourceHandle*) final;
     void didReceiveAuthenticationChallenge(WebCore::ResourceHandle*, const WebCore::AuthenticationChallenge&) final;
     void receivedCancellation(WebCore::ResourceHandle*, const WebCore::AuthenticationChallenge&) final;
-    bool usesAsyncCallbacks() final { return true; }
     bool loadingSynchronousXHR() final { return m_client.get().isSynchronous(); }
 #else
     // NetworkDataTaskClient
index d1cb19c..d6233c2 100644 (file)
@@ -23,9 +23,9 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ArgumentCodersMac_h
-#define ArgumentCodersMac_h
+#pragma once
 
+#include <objc/objc.h>
 #include <wtf/RetainPtr.h>
 
 OBJC_CLASS NSArray;
@@ -93,5 +93,3 @@ void encode(Encoder&, NSURL *);
 bool decode(Decoder&, RetainPtr<NSURL>&);
 
 } // namespace IPC
-
-#endif // ArgumentCodersMac_h
index 12d5b4d..1e34426 100644 (file)
@@ -173,20 +173,6 @@ static RetainPtr<CFURLRequestRef> createCFURLRequestFromSerializableRepresentati
     return WTFMove(cfRequest);
 }
 
-static RetainPtr<CFDictionaryRef> createSerializableRepresentation(NSURLRequest *request, CFTypeRef tokenNull)
-{
-    return createSerializableRepresentation([request _CFURLRequest], tokenNull);
-}
-
-static RetainPtr<NSURLRequest> createNSURLRequestFromSerializableRepresentation(CFDictionaryRef representation, CFTypeRef tokenNull)
-{
-    auto cfRequest = createCFURLRequestFromSerializableRepresentation(representation, tokenNull);
-    if (!cfRequest)
-        return nullptr;
-
-    return adoptNS([[NSURLRequest alloc] _initWithCFURLRequest:cfRequest.get()]);
-}
-
 #if USE(CFURLCONNECTION)
 void ArgumentCoder<ResourceRequest>::encodePlatformData(Encoder& encoder, const ResourceRequest& resourceRequest)
 {
@@ -217,7 +203,23 @@ void ArgumentCoder<ResourceRequest>::encodePlatformData(Encoder& encoder, const
     encoder.encodeEnum(resourceRequest.requester());
     encoder.encodeEnum(resourceRequest.cachePolicy());
 }
+
 #else
+
+static RetainPtr<CFDictionaryRef> createSerializableRepresentation(NSURLRequest *request, CFTypeRef tokenNull)
+{
+    return createSerializableRepresentation([request _CFURLRequest], tokenNull);
+}
+
+static RetainPtr<NSURLRequest> createNSURLRequestFromSerializableRepresentation(CFDictionaryRef representation, CFTypeRef tokenNull)
+{
+    auto cfRequest = createCFURLRequestFromSerializableRepresentation(representation, tokenNull);
+    if (!cfRequest)
+        return nullptr;
+    
+    return adoptNS([[NSURLRequest alloc] _initWithCFURLRequest:cfRequest.get()]);
+}
+    
 void ArgumentCoder<ResourceRequest>::encodePlatformData(Encoder& encoder, const ResourceRequest& resourceRequest)
 {
     RetainPtr<NSURLRequest> requestToSerialize = resourceRequest.nsURLRequest(DoNotUpdateHTTPBody);
index bf3285f..f0afd2e 100644 (file)
@@ -1,3 +1,13 @@
+2017-10-31  Alex Christensen  <achristensen@webkit.org>
+
+        Use asynchronous ResourceHandleClient calls for WebKit1
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+
+        Reviewed by Brady Eidson.
+
+        * WebCoreSupport/WebResourceLoadScheduler.cpp:
+        (WebResourceLoadScheduler::createPingHandle):
+
 2017-10-16  Ryan Haddad  <ryanhaddad@apple.com>
 
         Unreviewed, rolling out r223271.
index c4b5584..3b39264 100644 (file)
@@ -363,7 +363,7 @@ bool WebResourceLoadScheduler::HostInformation::limitRequests(ResourceLoadPriori
 void WebResourceLoadScheduler::startPingLoad(Frame& frame, ResourceRequest& request, const HTTPHeaderMap&, const FetchOptions& options, PingLoadCompletionHandler&& completionHandler)
 {
     // PingHandle manages its own lifetime, deleting itself when its purpose has been fulfilled.
-    new PingHandle(frame.loader().networkingContext(), request, options.credentials != FetchOptions::Credentials::Omit, PingHandle::UsesAsyncCallbacks::No, options.redirect == FetchOptions::Redirect::Follow, WTFMove(completionHandler));
+    new PingHandle(frame.loader().networkingContext(), request, options.credentials != FetchOptions::Credentials::Omit, options.redirect == FetchOptions::Redirect::Follow, WTFMove(completionHandler));
 }
 
 void WebResourceLoadScheduler::preconnectTo(NetworkingContext&, const URL&, StoredCredentialsPolicy, PreconnectCompletionHandler&&)
index 2a86ef1..cd4e20c 100644 (file)
@@ -1,3 +1,15 @@
+2017-10-31  Alex Christensen  <achristensen@webkit.org>
+
+        Use asynchronous ResourceHandleClient calls for WebKit1
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+
+        Reviewed by Brady Eidson.
+
+        * TestWebKitAPI/Tests/mac/SimplifyMarkup.mm:
+        (TestWebKitAPI::TEST):
+        The HTML being loaded contains an iframe, so testing if the main resource has loaded doesn't necessarily mean all subresources are loaded.
+        Wait until they are loaded before continuing the test.  This is a test of editing commands once the page has loaded, not a test of loading.
+
 2017-10-31  Commit Queue  <commit-queue@webkit.org>
 
         Unreviewed, rolling out r224143.
index 29b9f84..a7941fb 100644 (file)
@@ -64,6 +64,8 @@ TEST(WebKitLegacy, SimplifyMarkupTest)
     
     Util::run(&didFinishLoad);
     didFinishLoad = false;
+    while (![[[[webView1 mainFrameDocument] body] innerHTML] isEqualToString:[[[webView2 mainFrameDocument] body] innerHTML]])
+        Util::spinRunLoop(1);
 
     DOMDocument *document1 = webView1.get().mainFrameDocument;
     NSString* markupBefore = [[document1 body] innerHTML];