Unreviewed, rolling out r223271.
authorryanhaddad@apple.com <ryanhaddad@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 16 Oct 2017 16:12:18 +0000 (16:12 +0000)
committerryanhaddad@apple.com <ryanhaddad@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 16 Oct 2017 16:12:18 +0000 (16:12 +0000)
This change introduced LayoutTest failures on WK1.

Reverted changeset:

"Use asynchronous ResourceHandleClient calls for WebKit1"
https://bugs.webkit.org/show_bug.cgi?id=160677
https://trac.webkit.org/changeset/223271

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

53 files changed:
LayoutTests/ChangeLog
LayoutTests/TestExpectations
LayoutTests/platform/gtk/TestExpectations
LayoutTests/platform/ios-wk2/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/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 [new file with mode: 0644]
Source/WebCore/platform/network/cf/SynchronousResourceHandleCFURLConnectionDelegate.h [new file with mode: 0644]
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 [new file with mode: 0644]
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsDelegate.mm [new file with mode: 0644]
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm
Source/WebCore/platform/network/soup/ResourceHandleSoup.cpp
Source/WebKit/ChangeLog
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

index a615ec7..1a6ace9 100644 (file)
@@ -1,3 +1,15 @@
+2017-10-16  Ryan Haddad  <ryanhaddad@apple.com>
+
+        Unreviewed, rolling out r223271.
+
+        This change introduced LayoutTest failures on WK1.
+
+        Reverted changeset:
+
+        "Use asynchronous ResourceHandleClient calls for WebKit1"
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+        https://trac.webkit.org/changeset/223271
+
 2017-10-16  Per Arne Vollan  <pvollan@apple.com>
 
         Mark animations/play-state-in-shorthand.html as flaky on Windows.
index 2edaa20..0f5aaff 100644 (file)
@@ -39,9 +39,6 @@ http/tests/preload/viewport [ 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 ]
 
@@ -441,11 +438,6 @@ 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 ]
@@ -784,7 +776,6 @@ 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 9fdecec..8b9aa56 100644 (file)
@@ -1635,6 +1635,8 @@ 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 6aef372..0ab8426 100644 (file)
@@ -446,6 +446,7 @@ 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 aaead11..3205462 100644 (file)
@@ -297,6 +297,8 @@ 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 5d81cbd..59300c0 100644 (file)
@@ -264,6 +264,7 @@ 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 1af639b..edde932 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 onload="makeImage()">
+<body>
 <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 874c18c..3b49cd5 100644 (file)
@@ -4,15 +4,6 @@
   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 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-->
+    <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-->
   </div>
 </body>
 </html>
index 187443a..043d604 100644 (file)
@@ -1,3 +1,15 @@
+2017-10-16  Ryan Haddad  <ryanhaddad@apple.com>
+
+        Unreviewed, rolling out r223271.
+
+        This change introduced LayoutTest failures on WK1.
+
+        Reverted changeset:
+
+        "Use asynchronous ResourceHandleClient calls for WebKit1"
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+        https://trac.webkit.org/changeset/223271
+
 2017-10-16  Alejandro G. Castro  <alex@igalia.com>
 
         Make RealtimeIncomingVideoSources and RealtimeOutgoingVideoSources port agnostic
index 4cd5e06..66bcb16 100644 (file)
@@ -60,11 +60,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 d0113ba..5e4ec62 100644 (file)
@@ -562,6 +562,7 @@ 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 1904866..691a325 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 */; };
+               26FAE4CE1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 26FAE4CA1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.cpp */; };
+               26FAE4CF1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 26FAE4CB1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.h */; };
                2914E3071CAB5A440049966F /* AccessibilityAttachment.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2914E3051CAB5A440049966F /* AccessibilityAttachment.cpp */; };
                2914E3081CAB5A440049966F /* AccessibilityAttachment.h in Headers */ = {isa = PBXBuildFile; fileRef = 2914E3061CAB5A440049966F /* AccessibilityAttachment.h */; };
                2917B5611473496C0052C9D0 /* LayerFlushScheduler.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2917B55E1473496C0052C9D0 /* LayerFlushScheduler.cpp */; };
                E17B491616A9B094001C8839 /* TransitionEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E17B491416A9B093001C8839 /* TransitionEvent.h */; };
                E17B492116A9B8FF001C8839 /* JSTransitionEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E17B491F16A9B8FF001C8839 /* JSTransitionEvent.h */; };
                E17B492216A9B8FF001C8839 /* JSTransitionEvent.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E17B492016A9B8FF001C8839 /* JSTransitionEvent.cpp */; };
+               E180810E16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = E180810C16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.mm */; };
+               E180810F16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = E180810D16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.h */; };
                E180811216FCF42F00B80D07 /* SynchronousLoaderClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E180811016FCF42E00B80D07 /* SynchronousLoaderClient.cpp */; };
                E180811616FCF9CB00B80D07 /* SynchronousLoaderClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = E180811416FCF9CB00B80D07 /* SynchronousLoaderClient.mm */; };
                E180811716FCF9CB00B80D07 /* SynchronousLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E180811516FCF9CB00B80D07 /* SynchronousLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
                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 */,
                                E180811216FCF42F00B80D07 /* SynchronousLoaderClient.cpp in Sources */,
                                E180811616FCF9CB00B80D07 /* SynchronousLoaderClient.mm in Sources */,
                                442ABCD617D9262F00D30715 /* SynchronousLoaderClientCFNet.cpp in Sources */,
+                               26FAE4CE1852E3A5004C8C46 /* SynchronousResourceHandleCFURLConnectionDelegate.cpp in Sources */,
                                E45390AE0EAFF4B5003695C8 /* SystemMemoryIOS.cpp in Sources */,
                                5D5975B419635F1100D00878 /* SystemVersion.mm in Sources */,
                                463EB6221B8789E00096ED51 /* TagCollection.cpp in Sources */,
                                CD225C0B1C46FBF400140761 /* WebCoreNSURLSession.mm in Sources */,
                                B50F5B810E96CD9900AD71A6 /* WebCoreObjCExtras.mm in Sources */,
                                9BDD18271F7E05F400E8E577 /* WebCorePasteboardFileReader.cpp in Sources */,
+                               E180810E16FCECDF00B80D07 /* WebCoreResourceHandleAsDelegate.mm in Sources */,
                                E152551616FD2350003D7ADB /* WebCoreResourceHandleAsOperationQueueDelegate.mm in Sources */,
                                A14832C8187F673F00DA63A6 /* WebCoreThread.mm in Sources */,
                                A14832CB187F67B400DA63A6 /* WebCoreThreadRun.cpp in Sources */,
index 9287efa..a145664 100644 (file)
@@ -42,7 +42,7 @@ using namespace WebCore;
         return nil;
     }
 
-    resource = ArchiveResource::create(SharedBuffer::create(adoptNS([data copy]).get()), URL, MIMEType, textEncodingName, frameName, { });
+    resource = ArchiveResource::create(SharedBuffer::create(adoptNS([data copy]).get()), URL, MIMEType, textEncodingName, frameName, nil);
     if (!resource) {
         [self release];
         return nil;
index cc78f2b..f33f44a 100644 (file)
@@ -618,15 +618,12 @@ ResourceError ResourceLoader::cannotShowURLError()
     return frameLoader()->client().cannotShowURLError(m_request);
 }
 
-void ResourceLoader::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&& redirectResponse)
+ResourceRequest ResourceLoader::willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&& redirectResponse)
 {
-    RefPtr<ResourceHandle> protectedHandle(handle);
-    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse)) {
-        handle->continueWillSendRequest(WTFMove(request));
-        return;
-    }
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse))
+        return WTFMove(request);
     willSendRequestInternal(request, redirectResponse);
-    handle->continueWillSendRequest(WTFMove(request));
+    return WTFMove(request);
 }
 
 void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
@@ -634,14 +631,11 @@ void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent,
     didSendData(bytesSent, totalBytesToBeSent);
 }
 
-void ResourceLoader::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
+void ResourceLoader::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
 {
-    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response)) {
-        handle->continueDidReceiveResponse();
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response))
         return;
-    }
     didReceiveResponse(response);
-    handle->continueDidReceiveResponse();
 }
 
 void ResourceLoader::didReceiveData(ResourceHandle*, const char* data, unsigned length, int encodedDataLength)
@@ -712,10 +706,6 @@ 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 75f37c8..5cd5069 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 didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) override;
-    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
+    void didReceiveResponse(ResourceHandle*, 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)
-    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) override;
+    bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace& protectionSpace) override { return canAuthenticateAgainstProtectionSpace(protectionSpace); }
 #endif
     void receivedCancellation(ResourceHandle*, const AuthenticationChallenge& challenge) override { receivedCancellation(challenge); }
 #if PLATFORM(IOS)
index 113c687..ee25f9f 100644 (file)
@@ -485,14 +485,13 @@ RefPtr<ResourceHandle> ApplicationCacheGroup::createResourceHandle(const URL& ur
     return handle;
 }
 
-void ApplicationCacheGroup::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
+void ApplicationCacheGroup::didReceiveResponse(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;
     }
 
@@ -519,7 +518,6 @@ void ApplicationCacheGroup::didReceiveResponseAsync(ResourceHandle* handle, Reso
             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.
@@ -551,26 +549,12 @@ void ApplicationCacheGroup::didReceiveResponseAsync(ResourceHandle* handle, Reso
             // 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 34aab9f..5373845 100644 (file)
@@ -109,14 +109,10 @@ private:
     bool shouldUseCredentialStorage(ResourceHandle*) override { return true; }
 
     // ResourceHandleClient
-    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 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 didReceiveManifestResponse(const ResourceResponse&);
     void didReceiveManifestData(const char*, int);
index bce039e..9cff893 100644 (file)
@@ -74,12 +74,8 @@ class BlobResourceSynchronousLoader : public ResourceHandleClient {
 public:
     BlobResourceSynchronousLoader(ResourceError&, ResourceResponse&, Vector<char>&);
 
-    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
+    void didReceiveResponse(ResourceHandle*, ResourceResponse&&) override;
+    void didFail(ResourceHandle*, const ResourceError&) override;
 
 private:
     ResourceError& m_error;
@@ -94,26 +90,11 @@ BlobResourceSynchronousLoader::BlobResourceSynchronousLoader(ResourceError& erro
 {
 }
 
-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)
+void BlobResourceSynchronousLoader::didReceiveResponse(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;
     }
 
@@ -122,7 +103,6 @@ void BlobResourceSynchronousLoader::didReceiveResponseAsync(ResourceHandle* hand
     // 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)
@@ -179,6 +159,9 @@ void BlobResourceHandle::cancel()
 
 void BlobResourceHandle::continueDidReceiveResponse()
 {
+    ASSERT(m_async);
+    ASSERT(usesAsyncCallbacks());
+
     m_buffer.resize(bufferSize);
     readAsync();
 }
@@ -245,6 +228,10 @@ void BlobResourceHandle::getSizeForNext()
         if (m_async) {
             Ref<BlobResourceHandle> protectedThis(*this);
             notifyResponse();
+            if (!usesAsyncCallbacks()) {
+                m_buffer.resize(bufferSize);
+                readAsync();
+            }
         }
         return;
     }
@@ -435,6 +422,7 @@ 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())
@@ -458,6 +446,7 @@ void BlobResourceHandle::readAsync()
 void BlobResourceHandle::readDataAsync(const BlobDataItem& item)
 {
     ASSERT(isMainThread());
+    ASSERT(m_async);
     ASSERT(item.data().data());
 
     Ref<BlobResourceHandle> protectedThis(*this);
@@ -472,6 +461,7 @@ 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());
@@ -585,7 +575,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".
 
-    client()->didReceiveResponseAsync(this, WTFMove(response));
+    didReceiveResponse(WTFMove(response));
 }
 
 void BlobResourceHandle::notifyResponseOnError()
@@ -608,7 +598,7 @@ void BlobResourceHandle::notifyResponseOnError()
         break;
     }
 
-    client()->didReceiveResponseAsync(this, WTFMove(response));
+    didReceiveResponse(WTFMove(response));
 }
 
 void BlobResourceHandle::notifyReceiveData(const char* data, int bytesRead)
index 3e91da2..beb9c5a 100644 (file)
@@ -39,11 +39,17 @@ namespace WebCore {
 class PingHandle final : private ResourceHandleClient {
     WTF_MAKE_NONCOPYABLE(PingHandle); WTF_MAKE_FAST_ALLOCATED;
 public:
-    PingHandle(NetworkingContext* networkingContext, const ResourceRequest& request, bool shouldUseCredentialStorage, bool shouldFollowRedirects, WTF::CompletionHandler<void(const ResourceError&, const ResourceResponse&)>&& completionHandler)
+    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)
         : 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);
@@ -54,33 +60,26 @@ public:
     }
 
 private:
-    void willSendRequestAsync(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&) final
+    ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&) final
+    {
+        return m_shouldFollowRedirects ? request : ResourceRequest();
+    }
+    void willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&) final
     {
         m_currentRequest = WTFMove(request);
         if (m_shouldFollowRedirects) {
-            m_handle->continueWillSendRequest(ResourceRequest { m_currentRequest });
+            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 didReceiveResponseAsync(ResourceHandle*, ResourceResponse&& response) final
-    {
-        m_handle->continueDidReceiveResponse();
-        pingLoadComplete({ }, response);
-    }
+    void didReceiveResponse(ResourceHandle*, ResourceResponse&& response) final { 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 = { })
     {
@@ -104,6 +103,7 @@ private:
     Timer m_timeoutTimer;
     bool m_shouldUseCredentialStorage;
     bool m_shouldFollowRedirects;
+    UsesAsyncCallbacks m_usesAsyncCallbacks;
     WTF::CompletionHandler<void(const ResourceError&, const ResourceResponse&)> m_completionHandler;
 };
 
index e6aa508..bebcf88 100644 (file)
@@ -159,11 +159,15 @@ 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;
         }
     }
-    client()->didReceiveResponseAsync(this, WTFMove(response));
+    if (d->m_usesAsyncCallbacks)
+        d->m_client->didReceiveResponseAsync(this, WTFMove(response));
+    else {
+        d->m_client->didReceiveResponse(this, WTFMove(response));
+        platformContinueSynchronousDidReceiveResponse();
+    }
 }
 
 #if !USE(SOUP) && !USE(CURL)
@@ -240,4 +244,9 @@ void ResourceHandle::setDefersLoading(bool defers)
     platformSetDefersLoading(defers);
 }
 
+bool ResourceHandle::usesAsyncCallbacks() const
+{
+    return d->m_usesAsyncCallbacks;
+}
+
 } // namespace WebCore
index cc196d8..9e796f1 100644 (file)
@@ -70,7 +70,6 @@ typedef const struct __CFURLStorageSession* CFURLStorageSessionRef;
 
 namespace WTF {
 class SchedulePair;
-template<typename T> class MessageQueue;
 }
 
 namespace WebCore {
@@ -126,7 +125,7 @@ public:
 
 #if PLATFORM(COCOA) && !USE(CFURLCONNECTION)
     WEBCORE_EXPORT NSURLConnection *connection() const;
-    id makeDelegate(bool, WTF::MessageQueue<WTF::Function<void()>>*);
+    id makeDelegate(bool);
     id delegate();
     void releaseDelegate();
 #endif
@@ -238,6 +237,8 @@ public:
 protected:
     ResourceHandle(NetworkingContext*, const ResourceRequest&, ResourceHandleClient*, bool defersLoading, bool shouldContentSniff);
 
+    bool usesAsyncCallbacks() const;
+
 private:
     enum FailureType {
         NoFailure,
@@ -266,7 +267,7 @@ private:
 #endif
 
 #if USE(CFURLCONNECTION)
-    void createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, WTF::MessageQueue<WTF::Function<void()>>*, CFDictionaryRef clientProperties);
+    void createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, SchedulingBehavior, CFDictionaryRef clientProperties);
 #endif
 
 #if PLATFORM(MAC) && !USE(CFURLCONNECTION)
index ee7aca8..9487d96 100644 (file)
@@ -39,6 +39,28 @@ ResourceHandleClient::ResourceHandleClient()
 ResourceHandleClient::~ResourceHandleClient()
 {
 }
+    
+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 3912665..2618939 100644 (file)
@@ -63,8 +63,11 @@ 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);
     
@@ -73,17 +76,19 @@ 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&&) = 0;
+    WEBCORE_EXPORT virtual void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&);
 
     // Client will call ResourceHandle::continueDidReceiveResponse() when ready.
-    WEBCORE_EXPORT virtual void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) = 0;
+    WEBCORE_EXPORT virtual void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&);
 
 #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&) = 0;
+    WEBCORE_EXPORT virtual void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&);
 #endif
     // Client will pass an updated request using ResourceHandle::continueWillCacheResponse() when ready.
 #if USE(CFURLCONNECTION)
@@ -98,6 +103,9 @@ 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 fbb6cad..3b7144b 100644 (file)
@@ -80,6 +80,7 @@ public:
         , m_partition(request.cachePartition())
         , m_defersLoading(defersLoading)
         , m_shouldContentSniff(shouldContentSniff)
+        , m_usesAsyncCallbacks(client && client->usesAsyncCallbacks())
 #if USE(CFURLCONNECTION)
         , m_currentRequest(request)
 #endif
@@ -114,6 +115,7 @@ public:
 
     bool m_defersLoading;
     bool m_shouldContentSniff;
+    bool m_usesAsyncCallbacks;
 #if USE(CFURLCONNECTION)
     RetainPtr<CFURLConnectionRef> m_connection;
     ResourceRequest m_currentRequest;
index 2f12cbc..98c0b95 100644 (file)
@@ -36,17 +36,16 @@ SynchronousLoaderClient::~SynchronousLoaderClient()
 {
 }
 
-void SynchronousLoaderClient::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&&)
+ResourceRequest SynchronousLoaderClient::willSendRequest(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())) {
-        handle->continueWillSendRequest(WTFMove(request));
-        return;
-    }
+    if (protocolHostAndPortAreEqual(handle->firstRequest().url(), request.url()))
+        return WTFMove(request);
 
     ASSERT(m_error.isNull());
     m_error = platformBadResponseError();
-    handle->continueWillSendRequest({ });
+    m_isDone = true;
+    return { };
 }
 
 bool SynchronousLoaderClient::shouldUseCredentialStorage(ResourceHandle*)
@@ -56,17 +55,16 @@ bool SynchronousLoaderClient::shouldUseCredentialStorage(ResourceHandle*)
 }
 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-void SynchronousLoaderClient::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace&)
+bool SynchronousLoaderClient::canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&)
 {
     // FIXME: We should ask FrameLoaderClient. <http://webkit.org/b/65196>
-    handle->continueCanAuthenticateAgainstProtectionSpace(true);
+    return true;
 }
 #endif
 
-void SynchronousLoaderClient::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
+void SynchronousLoaderClient::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
 {
     m_response = WTFMove(response);
-    handle->continueDidReceiveResponse();
 }
 
 void SynchronousLoaderClient::didReceiveData(ResourceHandle*, const char* data, unsigned length, int /*encodedDataLength*/)
@@ -76,7 +74,7 @@ void SynchronousLoaderClient::didReceiveData(ResourceHandle*, const char* data,
 
 void SynchronousLoaderClient::didFinishLoading(ResourceHandle*)
 {
-    m_messageQueue.kill();
+    m_isDone = true;
 }
 
 void SynchronousLoaderClient::didFail(ResourceHandle*, const ResourceError& error)
@@ -84,8 +82,7 @@ void SynchronousLoaderClient::didFail(ResourceHandle*, const ResourceError& erro
     ASSERT(m_error.isNull());
 
     m_error = error;
-    
-    m_messageQueue.kill();
+    m_isDone = true;
 }
 
 }
index be9e73d..cb9b309 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#pragma once
+#ifndef SynchronousLoaderClient_h
+#define SynchronousLoaderClient_h
 
 #include "ResourceError.h"
 #include "ResourceHandleClient.h"
 #include "ResourceResponse.h"
-#include <wtf/Function.h>
-#include <wtf/MessageQueue.h>
 
 namespace WebCore {
 
@@ -41,26 +40,28 @@ public:
     const ResourceResponse& response() const { return m_response; }
     Vector<char>& mutableData() { return m_data; }
     const ResourceError& error() const { return m_error; }
-    MessageQueue<Function<void()>>& messageQueue() { return m_messageQueue; }
+    bool isDone() { return m_isDone; }
 
     WEBCORE_EXPORT static ResourceError platformBadResponseError();
 
 private:
-    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
+    ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
     bool shouldUseCredentialStorage(ResourceHandle*) override;
     void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge&) override;
-    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&) override;
+    void didReceiveResponse(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)
-    void canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle*, const ProtectionSpace&) override;
+    bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&) override;
 #endif
 
     bool m_allowStoredCredentials { false };
     ResourceResponse m_response;
     Vector<char> m_data;
     ResourceError m_error;
-    MessageQueue<Function<void()>> m_messageQueue;
+    bool m_isDone { false };
 };
 }
+
+#endif // SynchronousLoaderClient_h
index 49a9248..90c7c89 100644 (file)
@@ -59,14 +59,7 @@ 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 d8b45b3..9383824 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 long formDataAsNumber = static_cast<long long>(reinterpret_cast<intptr_t>(form->formData.get()));
-        return CFNumberCreate(0, kCFNumberLongLongType, &formDataAsNumber);
+        long formDataAsNumber = static_cast<long>(reinterpret_cast<intptr_t>(form->formData.get()));
+        return CFNumberCreate(0, kCFNumberLongType, &formDataAsNumber);
     }
 
     if (kCFCompareEqualTo == CFStringCompare(propertyName, formDataStreamLengthPropertyName(), 0))
index 7a6c2ff..63fce8b 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, MessageQueue<Function<void()>>* messageQueue, CFDictionaryRef clientProperties)
+void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, SchedulingBehavior schedulingBehavior, 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,6 +203,15 @@ 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)
@@ -228,7 +237,14 @@ void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool
     CFDictionaryAddValue(propertiesDictionary.get(), kCFURLConnectionSocketStreamProperties, streamProperties);
     CFRelease(streamProperties);
 
-    d->m_connectionDelegate = adoptRef(new ResourceHandleCFURLConnectionDelegateWithOperationQueue(this, messageQueue));
+#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->setupRequest(request.get());
 
     CFURLConnectionClient_V6 client = d->m_connectionDelegate->makeConnectionClient();
@@ -259,8 +275,9 @@ bool ResourceHandle::start()
     setCollectsTimingData();
 #endif
 
-    createCFURLConnection(shouldUseCredentialStorage, d->m_shouldContentSniff, nullptr, client()->connectionProperties(this).get());
-    ref();
+    SchedulingBehavior schedulingBehavior = client()->loadingSynchronousXHR() ? SchedulingBehavior::Synchronous : SchedulingBehavior::Asynchronous;
+
+    createCFURLConnection(shouldUseCredentialStorage, d->m_shouldContentSniff, schedulingBehavior, client()->connectionProperties(this).get());
 
     d->m_connectionDelegate->setupConnectionScheduling(d->m_connection.get());
     CFURLConnectionStart(d->m_connection.get());
@@ -308,15 +325,29 @@ ResourceRequest ResourceHandle::willSendRequest(ResourceRequest&& request, Resou
     }
 
     Ref<ResourceHandle> protectedThis(*this);
-    client()->willSendRequestAsync(this, WTFMove(request), WTFMove(redirectResponse));
-    return { };
+    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;
 }
 
 bool ResourceHandle::shouldUseCredentialStorage()
 {
     LOG(Network, "CFNet - shouldUseCredentialStorage()");
-    if (ResourceHandleClient* client = this->client())
+    if (ResourceHandleClient* client = this->client()) {
+        ASSERT(!d->m_usesAsyncCallbacks);
         return client->shouldUseCredentialStorage(this);
+    }
     return false;
 }
 
@@ -412,11 +443,16 @@ bool ResourceHandle::tryHandlePasswordBasedAuthentication(const AuthenticationCh
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
 {
-    if (auto* client = this->client())
-        client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
-    else
-        continueCanAuthenticateAgainstProtectionSpace(false);
-    return false; // Ignored by caller.
+    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);
 }
 #endif
 
@@ -538,10 +574,6 @@ 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));
@@ -563,39 +595,19 @@ void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* contex
         return;
     }
 
-    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);
+    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());
     CFURLConnectionStart(handle->connection());
 
-    do {
-        if (auto task = client.messageQueue().waitForMessage())
-            (*task)();
-    } while (!client.messageQueue().killed());
+    while (!client.isDone())
+        CFRunLoopRunInMode(synchronousLoadRunLoopMode(), UINT_MAX, true);
 
     error = client.error();
 
-    if (handle->connection())
-        CFURLConnectionCancel(handle->connection());
+    CFURLConnectionCancel(handle->connection());
 
     if (error.isNull())
         response = client.response();
index 8742c8a..41c5dc5 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, MessageQueue<Function<void()>>* messageQueue)
+ResourceHandleCFURLConnectionDelegateWithOperationQueue::ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle* handle)
     : ResourceHandleCFURLConnectionDelegate(handle)
-    , m_messageQueue(messageQueue)
+    , m_queue(dispatch_queue_create("com.apple.WebCore/CFNetwork", DISPATCH_QUEUE_SERIAL))
+    , m_semaphore(dispatch_semaphore_create(0))
 {
+    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
@@ -67,7 +68,8 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::releaseHandle()
     ResourceHandleCFURLConnectionDelegate::releaseHandle();
     m_requestResult = nullptr;
     m_cachedResponseResult = nullptr;
-    m_semaphore.signal();
+    m_boolResult = false;
+    dispatch_semaphore_signal(m_semaphore);
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::setupRequest(CFMutableURLRequestRef request)
@@ -81,62 +83,9 @@ 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)
 {
-#if PLATFORM(WIN)
-    installHookToRemoveCFNetworkMessageBlockingMainThread();
-#endif
-    CFRunLoopRef runLoop = getRunLoop();
-    CFURLConnectionScheduleWithRunLoop(connection, runLoop, kCFRunLoopDefaultMode);
-    CFURLConnectionScheduleDownloadWithRunLoop(connection, runLoop, kCFRunLoopDefaultMode);
+    CFURLConnectionSetDelegateDispatchQueue(connection, m_queue);
 }
 
 CFURLRequestRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest(CFURLRequestRef cfRequest, CFURLResponseRef originalRedirectResponse)
@@ -152,8 +101,17 @@ CFURLRequestRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSen
 
     ASSERT(!isMainThread());
     
-    auto work = [protectedThis = makeRef(*this), cfRequest = RetainPtr<CFURLRequestRef>(cfRequest), originalRedirectResponse = RetainPtr<CFURLResponseRef>(originalRedirectResponse)] () {
+    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& handle = protectedThis->m_handle;
+        auto& cfRequest = parameters.cfRequest;
         
         if (!protectedThis->hasHandle()) {
             protectedThis->continueWillSendRequest(nullptr);
@@ -162,28 +120,35 @@ 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(), originalRedirectResponse.get());
+        RetainPtr<CFURLResponseRef> redirectResponse = protectedThis->synthesizeRedirectResponseIfNecessary(cfRequest.get(), parameters.originalRedirectResponse.get());
         ASSERT(redirectResponse);
 
         ResourceRequest request = protectedThis->createResourceRequest(cfRequest.get(), redirectResponse.get());
         handle->willSendRequest(WTFMove(request), redirectResponse.get());
     };
     
-    if (m_messageQueue)
-        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
-    else
-        callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    ProtectedParameters parameters { makeRef(*this), cfRequest, originalRedirectResponse };
+    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
+    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
 
     return m_requestResult.leakRef();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse(CFURLConnectionRef connection, CFURLResponseRef cfResponse)
 {
-    auto work = [protectedThis = makeRef(*this), cfResponse = RetainPtr<CFURLResponseRef>(cfResponse), connection = RetainPtr<CFURLConnectionRef>(connection)] () {
+    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& handle = protectedThis->m_handle;
+        auto& cfResponse = parameters.cfResponse;
         
-        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
+        if (!protectedThis->hasHandle() || !handle->client()) {
             protectedThis->continueDidReceiveResponse();
             return;
         }
@@ -196,9 +161,7 @@ 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)
@@ -207,127 +170,86 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse
 #endif // !PLATFORM(IOS)
 
         ResourceResponse resourceResponse(cfResponse.get());
-        resourceResponse.setSource(ResourceResponse::Source::Network);
-#if !PLATFORM(WIN)
-        ResourceHandle::getConnectionTimingData(connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
-#endif
+        ResourceHandle::getConnectionTimingData(parameters.connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
 
         handle->didReceiveResponse(WTFMove(resourceResponse));
     };
 
-    if (m_messageQueue)
-        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
-    else
-        callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    ProtectedParameters parameters { makeRef(*this), connection, cfResponse };
+    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
+    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveData(CFDataRef data, CFIndex originalLength)
 {
-    auto work = [protectedThis = makeRef(*this), data = RetainPtr<CFDataRef>(data), originalLength = originalLength] () mutable {
+    callOnMainThread([protectedThis = makeRef(*this), data = RetainPtr<CFDataRef>(data), originalLength = originalLength] () mutable {
         auto& handle = protectedThis->m_handle;
-        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection())
+        if (!protectedThis->hasHandle() || !handle->client())
             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()
 {
-    auto work = [protectedThis = makeRef(*this)] () mutable {
+    callOnMainThread([protectedThis = makeRef(*this)] () mutable {
         auto& handle = protectedThis->m_handle;
-        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
-            protectedThis->m_handle->deref();
+        if (!protectedThis->hasHandle() || !handle->client())
             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)
 {
-    auto work = [protectedThis = makeRef(*this), error = RetainPtr<CFErrorRef>(error)] () mutable {
+    callOnMainThread([protectedThis = makeRef(*this), error = RetainPtr<CFErrorRef>(error)] () mutable {
         auto& handle = protectedThis->m_handle;
-        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
-            protectedThis->m_handle->deref();
+        if (!protectedThis->hasHandle() || !handle->client())
             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)
 {
-#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)] () {
+    struct ProtectedParameters {
+        Ref<ResourceHandleCFURLConnectionDelegateWithOperationQueue> protectedThis;
+        RetainPtr<CFCachedURLResponseRef> cachedResponse;
+    };
+    
+    auto work = [] (void* context) {
+        auto& parameters = *reinterpret_cast<ProtectedParameters*>(context);
+        auto& protectedThis = parameters.protectedThis;
         auto& handle = protectedThis->m_handle;
         
-        if (!protectedThis->hasHandle() || !handle->client() || !handle->connection()) {
+        if (!protectedThis->hasHandle() || !handle->client()) {
             protectedThis->continueWillCacheResponse(nullptr);
             return;
         }
 
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
-        handle->client()->willCacheResponseAsync(handle, cachedResponse.get());
+        handle->client()->willCacheResponseAsync(handle, parameters.cachedResponse.get());
     };
     
-    if (m_messageQueue)
-        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
-    else
-        callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    ProtectedParameters parameters { makeRef(*this), cachedResponse };
+    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
+    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     return m_cachedResponseResult.leakRef();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveChallenge(CFURLAuthChallengeRef challenge)
 {
-    auto work = [protectedThis = makeRef(*this), challenge = RetainPtr<CFURLAuthChallengeRef>(challenge)] () mutable {
+    callOnMainThread([protectedThis = makeRef(*this), challenge = RetainPtr<CFURLAuthChallengeRef>(challenge)] () mutable {
         auto& handle = protectedThis->m_handle;
         if (!protectedThis->hasHandle())
             return;
@@ -335,17 +257,12 @@ 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)
 {
-    auto work = [protectedThis = makeRef(*this), totalBytesWritten, totalBytesExpectedToWrite] () mutable {
+    callOnMainThread([protectedThis = makeRef(*this), totalBytesWritten, totalBytesExpectedToWrite] () mutable {
         auto& handle = protectedThis->m_handle;
         if (!protectedThis->hasHandle() || !handle->client() || !handle->connection())
             return;
@@ -353,23 +270,25 @@ 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 false;
+    return NO;
 }
 
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace(CFURLProtectionSpaceRef protectionSpace)
 {
-    auto work = [protectedThis = makeRef(*this), protectionSpace = RetainPtr<CFURLProtectionSpaceRef>(protectionSpace)] () mutable {
+    struct ProtectedParameters {
+        Ref<ResourceHandleCFURLConnectionDelegateWithOperationQueue> protectedThis;
+        RetainPtr<CFURLProtectionSpaceRef> protectionSpace;
+    };
+    
+    auto work = [] (void* context) {
+        auto& parameters = *reinterpret_cast<ProtectedParameters*>(context);
+        auto& protectedThis = parameters.protectedThis;
         auto& handle = protectedThis->m_handle;
         
         if (!protectedThis->hasHandle()) {
@@ -379,7 +298,7 @@ Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToPro
 
         LOG(Network, "CFNet - ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace(handle=%p) (%s)", handle, handle->firstRequest().url().string().utf8().data());
 
-        ProtectionSpace coreProtectionSpace = ProtectionSpace(protectionSpace.get());
+        ProtectionSpace coreProtectionSpace = ProtectionSpace(parameters.protectionSpace.get());
 #if PLATFORM(IOS)
         if (coreProtectionSpace.authenticationScheme() == ProtectionSpaceAuthenticationSchemeUnknown) {
             m_boolResult = false;
@@ -390,38 +309,37 @@ Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToPro
         handle->canAuthenticateAgainstProtectionSpace(coreProtectionSpace);
     };
     
-    if (m_messageQueue)
-        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
-    else
-        callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    ProtectedParameters parameters { makeRef(*this), protectionSpace };
+    dispatch_async_f(dispatch_get_main_queue(), &parameters, work);
+    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     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;
-    m_semaphore.signal();
+    dispatch_semaphore_signal(m_semaphore);
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueDidReceiveResponse()
 {
-    m_semaphore.signal();
+    dispatch_semaphore_signal(m_semaphore);
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::continueWillCacheResponse(CFCachedURLResponseRef response)
 {
     m_cachedResponseResult = response;
-    m_semaphore.signal();
+    dispatch_semaphore_signal(m_semaphore);
 }
 
+#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 6ad1e4f..bd84da3 100644 (file)
 #include "ResourceHandleCFURLConnectionDelegate.h"
 #include <CFNetwork/CFNetwork.h>
 #include <dispatch/queue.h>
-#include <wtf/Function.h>
-#include <wtf/MessageQueue.h>
-#include <wtf/threads/BinarySemaphore.h>
+#include <dispatch/semaphore.h>
 
 namespace WebCore {
 
 class ResourceHandleCFURLConnectionDelegateWithOperationQueue final : public ResourceHandleCFURLConnectionDelegate {
 public:
-    ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle*, MessageQueue<Function<void()>>*);
+    ResourceHandleCFURLConnectionDelegateWithOperationQueue(ResourceHandle*);
     virtual ~ResourceHandleCFURLConnectionDelegateWithOperationQueue();
 
 private:
@@ -57,21 +55,23 @@ 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
+#endif // USE(PROTECTION_SPACE_AUTH_CALLBACK)
 
-    BinarySemaphore m_semaphore;
-    MessageQueue<Function<void()>>* m_messageQueue { nullptr };
+    dispatch_queue_t m_queue;
+    dispatch_semaphore_t m_semaphore;
 
     RetainPtr<CFURLRequestRef> m_requestResult;
     RetainPtr<CFCachedURLResponseRef> m_cachedResponseResult;
-    bool m_boolResult { false };
+    bool m_boolResult;
 };
 
 } // namespace WebCore.
index 00e3a03..97016e3 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
new file mode 100644 (file)
index 0000000..205a6f3
--- /dev/null
@@ -0,0 +1,298 @@
+/*
+ * 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
new file mode 100644 (file)
index 0000000..c648932
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * 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 d550b08..1bcbd05 100644 (file)
@@ -350,7 +350,7 @@ void MultipartHandle::didReceiveResponse()
         response.setMimeType(mimeType.convertToASCIILowercase());
         response.setTextEncodingName(extractCharsetFromMediaType(contentType));
 
-        m_resourceHandle->didReceiveResponse(WTFMove(response));
+        d->client()->didReceiveResponse(m_resourceHandle, WTFMove(response));
     }
 }
 
index a5b500a..a34b301 100644 (file)
@@ -276,6 +276,7 @@ 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 6c5014e..500ed5b 100644 (file)
@@ -363,7 +363,12 @@ void ResourceHandleCurlDelegate::willSendRequest()
     }
 
     ResourceResponse responseCopy = response();
-    m_handle->client()->willSendRequestAsync(m_handle, WTFMove(newRequest), WTFMove(responseCopy));
+    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));
+    }
 }
 
 void ResourceHandleCurlDelegate::continueWillSendRequest(ResourceRequest&& request)
@@ -439,7 +444,7 @@ void ResourceHandleCurlDelegate::handleDataURL()
 
     if (base64) {
         data = decodeURLEscapeSequences(data);
-        m_handle->didReceiveResponse(WTFMove(response));
+        m_handle->client()->didReceiveResponse(m_handle, WTFMove(response));
 
         // didReceiveResponse might cause the client to be deleted.
         if (m_handle->client()) {
@@ -450,7 +455,7 @@ void ResourceHandleCurlDelegate::handleDataURL()
     } else {
         TextEncoding encoding(charset);
         data = decodeURLEscapeSequences(data, encoding);
-        m_handle->didReceiveResponse(WTFMove(response));
+        m_handle->client()->didReceiveResponse(m_handle, WTFMove(response));
 
         // didReceiveResponse might cause the client to be deleted.
         if (m_handle->client()) {
index 25bc3e7..43e0fa1 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)
@@ -203,6 +180,15 @@ 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) {
@@ -214,6 +200,16 @@ 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) {
@@ -348,8 +344,12 @@ 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 06826f1..3940dbe 100644 (file)
@@ -44,6 +44,7 @@
 #import "SharedBuffer.h"
 #import "SubresourceLoader.h"
 #import "SynchronousLoaderClient.h"
+#import "WebCoreResourceHandleAsDelegate.h"
 #import "WebCoreResourceHandleAsOperationQueueDelegate.h"
 #import "WebCoreURLResponse.h"
 #import <pal/spi/cf/CFNetworkSPI.h>
@@ -247,21 +248,48 @@ bool ResourceHandle::start()
 
 #if !PLATFORM(IOS)
     createNSURLConnection(
-        ResourceHandle::makeDelegate(shouldUseCredentialStorage, nullptr),
+        ResourceHandle::makeDelegate(shouldUseCredentialStorage),
         shouldUseCredentialStorage,
         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
         schedulingBehavior);
 #else
     createNSURLConnection(
-        ResourceHandle::makeDelegate(shouldUseCredentialStorage, nullptr),
+        ResourceHandle::makeDelegate(shouldUseCredentialStorage),
         shouldUseCredentialStorage,
         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
         schedulingBehavior,
         (NSDictionary *)client()->connectionProperties(this).get());
 #endif
 
-    [connection() setDelegateQueue:operationQueueForAsyncClients()];
-    [connection() start];
+    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;
 
     LOG(Network, "Handle %p starting connection %p for %@", this, connection(), firstRequest().nsURLRequest(DoNotUpdateHTTPBody));
     
@@ -302,6 +330,10 @@ 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)
@@ -312,15 +344,18 @@ void ResourceHandle::unschedule(SchedulePair& pair)
 
 #endif
 
-id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage, MessageQueue<Function<void()>>* queue)
+id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage)
 {
     ASSERT(!d->m_delegate);
 
     id <NSURLConnectionDelegate> delegate;
-    if (shouldUseCredentialStorage)
-        delegate = [[WebCoreResourceHandleAsOperationQueueDelegate alloc] initWithHandle:this messageQueue:queue];
-    else
-        delegate = [[WebCoreResourceHandleWithCredentialStorageAsOperationQueueDelegate alloc] initWithHandle:this messageQueue:queue];
+    if (d->m_usesAsyncCallbacks) {
+        if (shouldUseCredentialStorage)
+            delegate = [[WebCoreResourceHandleAsOperationQueueDelegate alloc] initWithHandle:this];
+        else
+            delegate = [[WebCoreResourceHandleWithCredentialStorageAsOperationQueueDelegate alloc] initWithHandle:this];
+    } else
+        delegate = [[WebCoreResourceHandleAsDelegate alloc] initWithHandle:this];
 
     d->m_delegate = delegate;
     [delegate release];
@@ -331,7 +366,7 @@ id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage, MessageQueue<Fu
 id ResourceHandle::delegate()
 {
     if (!d->m_delegate)
-        return makeDelegate(false, nullptr);
+        return makeDelegate(false);
     return d->m_delegate.get();
 }
 
@@ -374,26 +409,24 @@ void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* contex
     bool shouldUseCredentialStorage = storedCredentialsPolicy == StoredCredentialsPolicy::Use;
 #if !PLATFORM(IOS)
     handle->createNSURLConnection(
-        handle->makeDelegate(shouldUseCredentialStorage, &client.messageQueue()),
+        handle->makeDelegate(shouldUseCredentialStorage),
         shouldUseCredentialStorage,
         handle->shouldContentSniff() || context->localFileContentSniffingEnabled(),
         SchedulingBehavior::Synchronous);
 #else
     handle->createNSURLConnection(
-        handle->makeDelegate(shouldUseCredentialStorage, &client.messageQueue()), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
+        handle->makeDelegate(shouldUseCredentialStorage), // 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() setDelegateQueue:operationQueueForAsyncClients()];
+    [handle->connection() scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(NSString *)synchronousLoadRunLoopMode()];
     [handle->connection() start];
     
-    do {
-        if (auto task = client.messageQueue().waitForMessage())
-            (*task)();
-    } while (!client.messageQueue().killed());
+    while (!client.isDone())
+        [[NSRunLoop currentRunLoop] runMode:(NSString *)synchronousLoadRunLoopMode() beforeDate:[NSDate distantFuture]];
 
     error = client.error();
     
@@ -453,12 +486,24 @@ ResourceRequest ResourceHandle::willSendRequest(ResourceRequest&& request, Resou
         }
     }
 
-    client()->willSendRequestAsync(this, WTFMove(request), WTFMove(redirectResponse));
-    return { };
+    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;
 }
 
 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());
@@ -467,9 +512,17 @@ 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);
@@ -565,15 +618,22 @@ bool ResourceHandle::tryHandlePasswordBasedAuthentication(const AuthenticationCh
 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
 {
-    if (ResourceHandleClient* client = this->client())
-        client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
-    else
-        continueCanAuthenticateAgainstProtectionSpace(false);
-    return false; // Ignored by caller.
+    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);
 }
 
 void ResourceHandle::continueCanAuthenticateAgainstProtectionSpace(bool result)
 {
+    ASSERT(d->m_usesAsyncCallbacks);
+
     [(id)delegate() continueCanAuthenticateAgainstProtectionSpace:result];
 }
 #endif
@@ -659,6 +719,8 @@ 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
new file mode 100644 (file)
index 0000000..a873b48
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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
new file mode 100644 (file)
index 0000000..4c2a4fa
--- /dev/null
@@ -0,0 +1,228 @@
+/*
+ * 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 26a793b..03fc6e9 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> {
+@interface WebCoreResourceHandleAsOperationQueueDelegate : NSObject <NSURLConnectionDelegate, WebCoreResourceLoaderDelegate> {
     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;
 }
 
-- (void)detachHandle;
-- (id)initWithHandle:(WebCore::ResourceHandle*)handle messageQueue:(MessageQueue<Function<void()>>*)messageQueue;
+- (id)initWithHandle:(WebCore::ResourceHandle*)handle;
 - (void)continueWillSendRequest:(NSURLRequest *)newRequest;
 - (void)continueDidReceiveResponse;
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 - (void)continueCanAuthenticateAgainstProtectionSpace:(BOOL)canAuthenticate;
+#endif
 - (void)continueWillCacheResponse:(NSCachedURLResponse *)response;
 @end
 
index 04370d8..9651bae 100644 (file)
@@ -36,7 +36,6 @@
 #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>
@@ -45,7 +44,7 @@ using namespace WebCore;
 
 @implementation WebCoreResourceHandleAsOperationQueueDelegate
 
-- (id)initWithHandle:(ResourceHandle*)handle messageQueue:(MessageQueue<Function<void()>>*)messageQueue
+- (id)initWithHandle:(ResourceHandle*)handle
 {
     self = [self init];
     if (!self)
@@ -53,7 +52,6 @@ using namespace WebCore;
 
     m_handle = handle;
     m_semaphore = dispatch_semaphore_create(0);
-    m_messageQueue = messageQueue;
 
     return self;
 }
@@ -115,21 +113,17 @@ using namespace WebCore;
         LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]); 
 #endif
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), newRequest = RetainPtr<NSURLRequest>(newRequest), redirectResponse = RetainPtr<NSURLResponse>(redirectResponse)] () mutable {
+    RetainPtr<id> protector(self);
+
+    dispatch_async(dispatch_get_main_queue(), ^{
         if (!m_handle) {
             m_requestResult = nullptr;
             dispatch_semaphore_signal(m_semaphore);
             return;
         }
 
-        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);
+        m_handle->willSendRequest(newRequest, redirectResponse);
+    });
 
     dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     return m_requestResult.autorelease();
@@ -142,20 +136,16 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
 
-    auto work = [self, protectedSelf = RetainPtr<id>(self), challenge = RetainPtr<NSURLAuthenticationChallenge>(challenge)] () mutable {
+    dispatch_async(dispatch_get_main_queue(), ^{
         if (!m_handle) {
-            [[challenge sender] cancelAuthenticationChallenge:challenge.get()];
+            [[challenge sender] cancelAuthenticationChallenge:challenge];
             return;
         }
-        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);
+        m_handle->didReceiveAuthenticationChallenge(core(challenge));
+    });
 }
 
+#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
 - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
 {
     ASSERT(!isMainThread());
@@ -163,23 +153,21 @@ 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] : @"");
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), protectionSpace = RetainPtr<NSURLProtectionSpace>(protectionSpace)] () mutable {
+    RetainPtr<id> protector(self);
+
+    dispatch_async(dispatch_get_main_queue(), ^{
         if (!m_handle) {
             m_boolResult = NO;
             dispatch_semaphore_signal(m_semaphore);
             return;
         }
-        m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace.get()));
-    };
+        m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace));
+    });
 
-    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
 {
@@ -187,8 +175,9 @@ 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]);
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), r = RetainPtr<NSURLResponse>(r), connection = RetainPtr<NSURLConnection>(connection)] () mutable {
-        RefPtr<ResourceHandle> protectedHandle(m_handle);
+    RetainPtr<id> protector(self);
+
+    dispatch_async(dispatch_get_main_queue(), ^{
         if (!m_handle || !m_handle->client()) {
             dispatch_semaphore_signal(m_semaphore);
             return;
@@ -204,18 +193,12 @@ using namespace WebCore;
         if ([m_handle->firstRequest().nsURLRequest(DoNotUpdateHTTPBody) _propertyForKey:@"ForceHTMLMIMEType"])
             [r _setMIMEType:@"text/html"];
 
-        ResourceResponse resourceResponse(r.get());
-        resourceResponse.setSource(ResourceResponse::Source::Network);
-        ResourceHandle::getConnectionTimingData(connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
+        ResourceResponse resourceResponse(r);
+        ResourceHandle::getConnectionTimingData(connection, 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);
 }
 
@@ -227,7 +210,7 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), data = RetainPtr<NSData>(data)] () mutable {
+    dispatch_async(dispatch_get_main_queue(), ^{
         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.
@@ -237,13 +220,8 @@ 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.get()), -1);
-    };
-
-    if (m_messageQueue)
-        m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
-    else
-        dispatch_async(dispatch_get_main_queue(), work);
+        m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(data), -1);
+    });
 }
 
 - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
@@ -254,16 +232,11 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), totalBytesWritten = totalBytesWritten, totalBytesExpectedToWrite = totalBytesExpectedToWrite] () mutable {
+    dispatch_async(dispatch_get_main_queue(), ^{
         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
@@ -273,21 +246,12 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
 
-    auto task = [self = self, protectedSelf = RetainPtr<id>(self)] () mutable {
+    dispatch_async(dispatch_get_main_queue(), ^{
         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
@@ -297,21 +261,12 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), error = RetainPtr<NSError>(error)] () mutable {
+    dispatch_async(dispatch_get_main_queue(), ^{
         if (!m_handle || !m_handle->client())
             return;
 
-        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);
+        m_handle->client()->didFail(m_handle, error);
+    });
 }
 
 
@@ -322,20 +277,17 @@ using namespace WebCore;
 
     LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
 
-    auto work = [self = self, protectedSelf = RetainPtr<id>(self), cachedResponse = RetainPtr<NSCachedURLResponse>(cachedResponse)] () mutable {
+    RetainPtr<id> protector(self);
+
+    dispatch_async(dispatch_get_main_queue(), ^{
         if (!m_handle || !m_handle->client()) {
             m_cachedResponseResult = nullptr;
             dispatch_semaphore_signal(m_semaphore);
             return;
         }
 
-        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);
+        m_handle->client()->willCacheResponseAsync(m_handle, cachedResponse);
+    });
 
     dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
     return m_cachedResponseResult.autorelease();
index 2070b8c..de1f49e 100644 (file)
@@ -355,7 +355,13 @@ static void doRedirect(ResourceHandle* handle)
     cleanupSoupRequestOperation(handle);
 
     ResourceResponse responseCopy = d->m_response;
-    d->client()->willSendRequestAsync(handle, WTFMove(newRequest), WTFMove(responseCopy));
+    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));
+    }
+
 }
 
 static void redirectSkipCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
@@ -1028,11 +1034,13 @@ 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 943b303..b1a9f4f 100644 (file)
@@ -1,3 +1,15 @@
+2017-10-16  Ryan Haddad  <ryanhaddad@apple.com>
+
+        Unreviewed, rolling out r223271.
+
+        This change introduced LayoutTest failures on WK1.
+
+        Reverted changeset:
+
+        "Use asynchronous ResourceHandleClient calls for WebKit1"
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+        https://trac.webkit.org/changeset/223271
+
 2017-10-13  Youenn Fablet  <youenn@apple.com>
 
         Implement listing origins for which CacheStorage is storing data
index a196dff..c6ff15a 100644 (file)
@@ -71,18 +71,6 @@ 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 1b441f6..4a42cc2 100644 (file)
@@ -49,10 +49,7 @@ private:
     void didReceiveBuffer(WebCore::ResourceHandle*, Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) final;
     void didFinishLoading(WebCore::ResourceHandle*) final;
     void didFail(WebCore::ResourceHandle*, const WebCore::ResourceError&) final;
-    void willSendRequestAsync(WebCore::ResourceHandle*, WebCore::ResourceRequest&&, WebCore::ResourceResponse&&) final;
-#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
-    void canAuthenticateAgainstProtectionSpaceAsync(WebCore::ResourceHandle*, const WebCore::ProtectionSpace&) final;
-#endif
+    bool usesAsyncCallbacks() final { return true; }
 
     Download& m_download;
     String m_destinationPath;
index 368c7c0..db4e9e9 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, loadParameters.shouldFollowRedirects, WTFMove(completionHandler));
+    new PingHandle(context.ptr(), loadParameters.request, loadParameters.storedCredentialsPolicy == StoredCredentialsPolicy::Use, PingHandle::UsesAsyncCallbacks::Yes, loadParameters.shouldFollowRedirects, WTFMove(completionHandler));
 #endif
 }
 
index de26982..d697298 100644 (file)
@@ -125,6 +125,7 @@ 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 d6233c2..d1cb19c 100644 (file)
@@ -23,9 +23,9 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#pragma once
+#ifndef ArgumentCodersMac_h
+#define ArgumentCodersMac_h
 
-#include <objc/objc.h>
 #include <wtf/RetainPtr.h>
 
 OBJC_CLASS NSArray;
@@ -93,3 +93,5 @@ void encode(Encoder&, NSURL *);
 bool decode(Decoder&, RetainPtr<NSURL>&);
 
 } // namespace IPC
+
+#endif // ArgumentCodersMac_h
index 1e34426..12d5b4d 100644 (file)
@@ -173,6 +173,20 @@ 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)
 {
@@ -203,23 +217,7 @@ 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 1af61ed..bf3285f 100644 (file)
@@ -1,3 +1,15 @@
+2017-10-16  Ryan Haddad  <ryanhaddad@apple.com>
+
+        Unreviewed, rolling out r223271.
+
+        This change introduced LayoutTest failures on WK1.
+
+        Reverted changeset:
+
+        "Use asynchronous ResourceHandleClient calls for WebKit1"
+        https://bugs.webkit.org/show_bug.cgi?id=160677
+        https://trac.webkit.org/changeset/223271
+
 2017-10-12  Alex Christensen  <achristensen@webkit.org>
 
         Use asynchronous ResourceHandleClient calls for WebKit1
index 3b39264..c4b5584 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, options.redirect == FetchOptions::Redirect::Follow, WTFMove(completionHandler));
+    new PingHandle(frame.loader().networkingContext(), request, options.credentials != FetchOptions::Credentials::Omit, PingHandle::UsesAsyncCallbacks::No, options.redirect == FetchOptions::Redirect::Follow, WTFMove(completionHandler));
 }
 
 void WebResourceLoadScheduler::preconnectTo(NetworkingContext&, const URL&, StoredCredentialsPolicy, PreconnectCompletionHandler&&)