Title: [279461] trunk
Revision
279461
Author
you...@apple.com
Date
2021-07-01 03:37:39 -0700 (Thu, 01 Jul 2021)

Log Message

[Cocoa] Migrate WebRTC UDP socket handling to NW API
https://bugs.webkit.org/show_bug.cgi?id=227210
LayoutTests/imported/w3c:

Reviewed by Eric Carlson.

Rebasing tests as timing changes a bit.
This aligns with Chrome and Firefox behavior.

* web-platform-tests/webrtc/no-media-call-expected.txt:
* web-platform-tests/webrtc/promises-call-expected.txt:

Source/ThirdParty/libwebrtc:

Reviewed by Eric Carlson.

* Configurations/libwebrtc.iOS.exp:
* Configurations/libwebrtc.iOSsim.exp:
* Configurations/libwebrtc.mac.exp:

Source/WebCore:

Reviewed by Eric Carlson.

Add infrastructure to new experimental feature flag for NW backed UDP sockets.

* page/RuntimeEnabledFeatures.h:
(WebCore::RuntimeEnabledFeatures::webRTCPlatformTCPSocketsEnabled const):
(WebCore::RuntimeEnabledFeatures::setWebRTCPlatformTCPSocketsEnabled):
(WebCore::RuntimeEnabledFeatures::webRTCPlatformUDPSocketsEnabled const):
(WebCore::RuntimeEnabledFeatures::setWebRTCPlatformUDPSocketsEnabled):

Source/WebKit:

Reviewed by Eric Carlson.

Migrate UDP socket handling from WebRTC physical socket server to nw API for Cocoa ports.

For each UDP socket opened, we open a nw_listener that will listen to inbound connections.
On inbound connection, we receive a nw_connection that we store in a address -> connection map.

Whenever sending a packet, we look at the remote address.
If needed, we create a nw_connection to that particular remote address and store it in the address -> connection map.
We then use the pre-existing or newly created nw_connection to send the packet.

Make sure to cancel NW connection in case of failure before releasing the socket.

Covered by existing tests

* NetworkProcess/webrtc/NetworkRTCProvider.cpp:
(WebKit::NetworkRTCProvider::createUDPSocket):
(WebKit::NetworkRTCProvider::createClientTCPSocket):
* NetworkProcess/webrtc/NetworkRTCProvider.h:
(WebKit::NetworkRTCProvider::setPlatformTCPSocketsEnabled):
(WebKit::NetworkRTCProvider::setPlatformUDPSocketsEnabled):
* NetworkProcess/webrtc/NetworkRTCProvider.messages.in:
* NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.h: Copied from Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h.
* NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.mm: Renamed from Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm.
(WebKit::tcpSocketQueue):
(WebKit::NetworkRTCTCPSocketCocoa::createClientTCPSocket):
(WebKit::NetworkRTCTCPSocketCocoa::NetworkRTCTCPSocketCocoa):
(WebKit::NetworkRTCTCPSocketCocoa::close):
(WebKit::NetworkRTCTCPSocketCocoa::setOption):
(WebKit::NetworkRTCTCPSocketCocoa::createMessageBuffer):
(WebKit::NetworkRTCTCPSocketCocoa::sendTo):
* NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.h: Added.
(WTF::DefaultHash<rtc::SocketAddress>::hash):
(WTF::DefaultHash<rtc::SocketAddress>::equal):
(WTF::HashTraits<rtc::SocketAddress>::emptyValue):
(WTF::HashTraits<rtc::SocketAddress>::constructDeletedValue):
(WTF::HashTraits<rtc::SocketAddress>::isDeletedValue):
* NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.mm: Added.
(WebKit::NetworkRTCUDPSocketCocoaConnections::create):
(WebKit::NetworkRTCUDPSocketCocoaConnections::WTF_GUARDED_BY_LOCK):
(WebKit::udpSocketQueue):
(WebKit::NetworkRTCUDPSocketCocoa::createUDPSocket):
(WebKit::NetworkRTCUDPSocketCocoa::NetworkRTCUDPSocketCocoa):
(WebKit::NetworkRTCUDPSocketCocoa::~NetworkRTCUDPSocketCocoa):
(WebKit::NetworkRTCUDPSocketCocoa::close):
(WebKit::NetworkRTCUDPSocketCocoa::setOption):
(WebKit::NetworkRTCUDPSocketCocoa::sendTo):
(WebKit::NetworkRTCUDPSocketCocoaConnections::NetworkRTCUDPSocketCocoaConnections):
(WebKit::NetworkRTCUDPSocketCocoaConnections::close):
(WebKit::NetworkRTCUDPSocketCocoaConnections::setOption):
(WebKit::processUDPData):
(WebKit::NetworkRTCUDPSocketCocoaConnections::createNWConnection):
(WebKit::NetworkRTCUDPSocketCocoaConnections::setupNWConnection):
(WebKit::NetworkRTCUDPSocketCocoaConnections::sendTo):
* SourcesCocoa.txt:
* WebKit.xcodeproj/project.pbxproj:
* WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp:
(WebKit::LibWebRTCSocketFactory::setConnection):

Source/WTF:

Reviewed by Eric Carlson.

Add a new experimental flag for NW backed UDP sockets.

* Scripts/Preferences/WebPreferencesExperimental.yaml:

LayoutTests:

<rdar://problem/79859045>

Reviewed by Eric Carlson.

* platform/ios-simulator-wk2/TestExpectations:
Mark test as failed, as this test is using unsupported API (transport).

Modified Paths

Added Paths

Removed Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (279460 => 279461)


--- trunk/LayoutTests/ChangeLog	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/LayoutTests/ChangeLog	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,5 +1,16 @@
 2021-07-01  Youenn Fablet  <you...@apple.com>
 
+        [Cocoa] Migrate WebRTC UDP socket handling to NW API
+        https://bugs.webkit.org/show_bug.cgi?id=227210
+        <rdar://problem/79859045>
+
+        Reviewed by Eric Carlson.
+
+        * platform/ios-simulator-wk2/TestExpectations:
+        Mark test as failed, as this test is using unsupported API (transport).
+
+2021-07-01  Youenn Fablet  <you...@apple.com>
+
         RealtimeIncomingAudioSourceCocoa should support other sample rate than 48000
         https://bugs.webkit.org/show_bug.cgi?id=227439
 

Modified: trunk/LayoutTests/imported/w3c/ChangeLog (279460 => 279461)


--- trunk/LayoutTests/imported/w3c/ChangeLog	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/LayoutTests/imported/w3c/ChangeLog	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,3 +1,16 @@
+2021-07-01  Youenn Fablet  <you...@apple.com>
+
+        [Cocoa] Migrate WebRTC UDP socket handling to NW API
+        https://bugs.webkit.org/show_bug.cgi?id=227210
+
+        Reviewed by Eric Carlson.
+
+        Rebasing tests as timing changes a bit.
+        This aligns with Chrome and Firefox behavior.
+
+        * web-platform-tests/webrtc/no-media-call-expected.txt:
+        * web-platform-tests/webrtc/promises-call-expected.txt:
+
 2021-07-01  Emilio Cobos Álvarez  <emi...@crisal.io>
 
         Support unprefixed :autofill pseudo-class.

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webrtc/no-media-call-expected.txt (279460 => 279461)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webrtc/no-media-call-expected.txt	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webrtc/no-media-call-expected.txt	2021-07-01 10:37:39 UTC (rev 279461)
@@ -2,5 +2,5 @@
 PASS Can set up a basic WebRTC call with no data.
 iceConnectionState info
 
-First: completed
+First: connected
 Second: connected

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webrtc/promises-call-expected.txt (279460 => 279461)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webrtc/promises-call-expected.txt	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webrtc/promises-call-expected.txt	2021-07-01 10:37:39 UTC (rev 279461)
@@ -2,5 +2,5 @@
 PASS Can set up a basic WebRTC call with only data using promises.
 iceConnectionState info
 
-First: completed
+First: connected
 Second: connected

Modified: trunk/LayoutTests/platform/ios-simulator-wk2/TestExpectations (279460 => 279461)


--- trunk/LayoutTests/platform/ios-simulator-wk2/TestExpectations	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/LayoutTests/platform/ios-simulator-wk2/TestExpectations	2021-07-01 10:37:39 UTC (rev 279461)
@@ -91,6 +91,7 @@
 webkit.org/b/214661 [ Debug ] imported/w3c/web-platform-tests/webrtc/RTCSctpTransport-events.html [ Skip ]
 webkit.org/b/214730 [ Debug ] webrtc/simulcast-h264.html [ Skip ]
 imported/w3c/web-platform-tests/webrtc/RTCPeerConnection-candidate-in-sdp.https.html [ Pass Failure ]
+imported/w3c/web-platform-tests/webrtc/protocol/crypto-suite.https.html [ Failure ]
 
 webkit.org/b/214358 fast/scrolling/ios/programmatic-scroll-while-zoomed.html [ Pass Failure ]
 

Modified: trunk/Source/ThirdParty/libwebrtc/ChangeLog (279460 => 279461)


--- trunk/Source/ThirdParty/libwebrtc/ChangeLog	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/ThirdParty/libwebrtc/ChangeLog	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,3 +1,14 @@
+2021-07-01  Youenn Fablet  <you...@apple.com>
+
+        [Cocoa] Migrate WebRTC UDP socket handling to NW API
+        https://bugs.webkit.org/show_bug.cgi?id=227210
+
+        Reviewed by Eric Carlson.
+
+        * Configurations/libwebrtc.iOS.exp:
+        * Configurations/libwebrtc.iOSsim.exp:
+        * Configurations/libwebrtc.mac.exp:
+
 2021-06-30  Truitt Savell  <tsav...@apple.com>
 
         Unreviewed, reverting r279405.

Modified: trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.iOS.exp (279460 => 279461)


--- trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.iOS.exp	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.iOS.exp	2021-07-01 10:37:39 UTC (rev 279461)
@@ -321,3 +321,6 @@
 __ZN6webrtc27CreatePeerConnectionFactoryEPN3rtc6ThreadES2_S2_NS0_13scoped_refptrINS_17AudioDeviceModuleEEENS3_INS_19AudioEncoderFactoryEEENS3_INS_19AudioDecoderFactoryEEENSt3__110unique_ptrINS_19VideoEncoderFactoryENSA_14default_deleteISC_EEEENSB_INS_19VideoDecoderFactoryENSD_ISG_EEEENS3_INS_10AudioMixerEEENS3_INS_15AudioProcessingEEEPNS_19AudioFrameProcessorE
 __ZNK6webrtc23RtpTransceiverInterface26HeaderExtensionsNegotiatedEv
 __ZN6webrtc30PeerConnectionFactoryInterface20CreatePeerConnectionERKNS_23PeerConnectionInterface16RTCConfigurationENS_26PeerConnectionDependenciesE
+__ZNK3rtc13SocketAddress4HashEv
+__ZNK3rtc13SocketAddresseqERKS0_
+__ZNK3rtc9IPAddress5IsNilEv

Modified: trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.iOSsim.exp (279460 => 279461)


--- trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.iOSsim.exp	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.iOSsim.exp	2021-07-01 10:37:39 UTC (rev 279461)
@@ -321,3 +321,6 @@
 __ZN6webrtc27CreatePeerConnectionFactoryEPN3rtc6ThreadES2_S2_NS0_13scoped_refptrINS_17AudioDeviceModuleEEENS3_INS_19AudioEncoderFactoryEEENS3_INS_19AudioDecoderFactoryEEENSt3__110unique_ptrINS_19VideoEncoderFactoryENSA_14default_deleteISC_EEEENSB_INS_19VideoDecoderFactoryENSD_ISG_EEEENS3_INS_10AudioMixerEEENS3_INS_15AudioProcessingEEEPNS_19AudioFrameProcessorE
 __ZNK6webrtc23RtpTransceiverInterface26HeaderExtensionsNegotiatedEv
 __ZN6webrtc30PeerConnectionFactoryInterface20CreatePeerConnectionERKNS_23PeerConnectionInterface16RTCConfigurationENS_26PeerConnectionDependenciesE
+__ZNK3rtc13SocketAddress4HashEv
+__ZNK3rtc13SocketAddresseqERKS0_
+__ZNK3rtc9IPAddress5IsNilEv

Modified: trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.mac.exp (279460 => 279461)


--- trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.mac.exp	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/ThirdParty/libwebrtc/Configurations/libwebrtc.mac.exp	2021-07-01 10:37:39 UTC (rev 279461)
@@ -321,3 +321,6 @@
 __ZN6webrtc27CreatePeerConnectionFactoryEPN3rtc6ThreadES2_S2_NS0_13scoped_refptrINS_17AudioDeviceModuleEEENS3_INS_19AudioEncoderFactoryEEENS3_INS_19AudioDecoderFactoryEEENSt3__110unique_ptrINS_19VideoEncoderFactoryENSA_14default_deleteISC_EEEENSB_INS_19VideoDecoderFactoryENSD_ISG_EEEENS3_INS_10AudioMixerEEENS3_INS_15AudioProcessingEEEPNS_19AudioFrameProcessorE
 __ZNK6webrtc23RtpTransceiverInterface26HeaderExtensionsNegotiatedEv
 __ZN6webrtc30PeerConnectionFactoryInterface20CreatePeerConnectionERKNS_23PeerConnectionInterface16RTCConfigurationENS_26PeerConnectionDependenciesE
+__ZNK3rtc13SocketAddress4HashEv
+__ZNK3rtc13SocketAddresseqERKS0_
+__ZNK3rtc9IPAddress5IsNilEv

Modified: trunk/Source/WTF/ChangeLog (279460 => 279461)


--- trunk/Source/WTF/ChangeLog	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WTF/ChangeLog	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,3 +1,14 @@
+2021-07-01  Youenn Fablet  <you...@apple.com>
+
+        [Cocoa] Migrate WebRTC UDP socket handling to NW API
+        https://bugs.webkit.org/show_bug.cgi?id=227210
+
+        Reviewed by Eric Carlson.
+
+        Add a new experimental flag for NW backed UDP sockets.
+
+        * Scripts/Preferences/WebPreferencesExperimental.yaml:
+
 2021-07-01  Jer Noble  <jer.no...@apple.com>
 
         [Mac] (Re-)enable GroupActivities after upstreaming

Modified: trunk/Source/WTF/Scripts/Preferences/WebPreferencesExperimental.yaml (279460 => 279461)


--- trunk/Source/WTF/Scripts/Preferences/WebPreferencesExperimental.yaml	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WTF/Scripts/Preferences/WebPreferencesExperimental.yaml	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1297,10 +1297,10 @@
     WebCore:
       default: false
 
-WebRTCPlatformSocketsEnabled:
+WebRTCPlatformTCPSocketsEnabled:
   type: bool
-  humanReadableName: "WebRTC Platform Sockets"
-  humanReadableDescription: "Enable WebRTC Platform Sockets"
+  humanReadableName: "WebRTC Platform TCP Sockets"
+  humanReadableDescription: "Enable WebRTC Platform TCP Sockets"
   webcoreBinding: RuntimeEnabledFeatures
   condition: ENABLE(WEB_RTC)
   defaultValue:
@@ -1307,6 +1307,16 @@
     WebKit:
       default: true
 
+WebRTCPlatformUDPSocketsEnabled:
+  type: bool
+  humanReadableName: "WebRTC Platform UDP Sockets"
+  humanReadableDescription: "Enable WebRTC Platform UDP Sockets"
+  webcoreBinding: RuntimeEnabledFeatures
+  condition: ENABLE(WEB_RTC)
+  defaultValue:
+    WebKit:
+      default: false
+
 WebRTCVP9Profile0CodecEnabled:
   type: bool
   humanReadableName: "WebRTC VP9 profile 0 codec"

Modified: trunk/Source/WebCore/ChangeLog (279460 => 279461)


--- trunk/Source/WebCore/ChangeLog	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebCore/ChangeLog	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,3 +1,18 @@
+2021-07-01  Youenn Fablet  <you...@apple.com>
+
+        [Cocoa] Migrate WebRTC UDP socket handling to NW API
+        https://bugs.webkit.org/show_bug.cgi?id=227210
+
+        Reviewed by Eric Carlson.
+
+        Add infrastructure to new experimental feature flag for NW backed UDP sockets.
+
+        * page/RuntimeEnabledFeatures.h:
+        (WebCore::RuntimeEnabledFeatures::webRTCPlatformTCPSocketsEnabled const):
+        (WebCore::RuntimeEnabledFeatures::setWebRTCPlatformTCPSocketsEnabled):
+        (WebCore::RuntimeEnabledFeatures::webRTCPlatformUDPSocketsEnabled const):
+        (WebCore::RuntimeEnabledFeatures::setWebRTCPlatformUDPSocketsEnabled):
+
 2021-07-01  Carlos Garcia Campos  <cgar...@igalia.com>
 
         [Cairo] Simplify GraphicsContextCairo creation

Modified: trunk/Source/WebCore/page/RuntimeEnabledFeatures.h (279460 => 279461)


--- trunk/Source/WebCore/page/RuntimeEnabledFeatures.h	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebCore/page/RuntimeEnabledFeatures.h	2021-07-01 10:37:39 UTC (rev 279461)
@@ -163,8 +163,10 @@
     void setWebRTCMDNSICECandidatesEnabled(bool isEnabled) { m_isWebRTCMDNSICECandidatesEnabled = isEnabled; }
     bool webRTCH264SimulcastEnabled() const { return m_isWebRTCH264SimulcastEnabled; }
     void setWebRTCH264SimulcastEnabled(bool isEnabled) { m_isWebRTCH264SimulcastEnabled = isEnabled; }
-    bool webRTCPlatformSocketsEnabled() const { return m_isWebRTCPlatformSocketsEnabled; }
-    void setWebRTCPlatformSocketsEnabled(bool isEnabled) { m_isWebRTCPlatformSocketsEnabled = isEnabled; }
+    bool webRTCPlatformTCPSocketsEnabled() const { return m_isWebRTCPlatformTCPSocketsEnabled; }
+    void setWebRTCPlatformTCPSocketsEnabled(bool isEnabled) { m_isWebRTCPlatformTCPSocketsEnabled = isEnabled; }
+    bool webRTCPlatformUDPSocketsEnabled() const { return m_isWebRTCPlatformUDPSocketsEnabled; }
+    void setWebRTCPlatformUDPSocketsEnabled(bool isEnabled) { m_isWebRTCPlatformUDPSocketsEnabled = isEnabled; }
 #endif
 
 #if ENABLE(DATALIST_ELEMENT)
@@ -319,7 +321,8 @@
     bool m_isWebRTCVP9Profile0CodecEnabled { false };
     bool m_isWebRTCVP9Profile2CodecEnabled { false };
     bool m_isWebRTCH264LowLatencyEncoderEnabled { false };
-    bool m_isWebRTCPlatformSocketsEnabled { false };
+    bool m_isWebRTCPlatformTCPSocketsEnabled { false };
+    bool m_isWebRTCPlatformUDPSocketsEnabled { false };
 #endif
 
 #if ENABLE(DATALIST_ELEMENT)

Modified: trunk/Source/WebKit/ChangeLog (279460 => 279461)


--- trunk/Source/WebKit/ChangeLog	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/ChangeLog	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,3 +1,67 @@
+2021-07-01  Youenn Fablet  <you...@apple.com>
+
+        [Cocoa] Migrate WebRTC UDP socket handling to NW API
+        https://bugs.webkit.org/show_bug.cgi?id=227210
+
+        Reviewed by Eric Carlson.
+
+        Migrate UDP socket handling from WebRTC physical socket server to nw API for Cocoa ports.
+
+        For each UDP socket opened, we open a nw_listener that will listen to inbound connections.
+        On inbound connection, we receive a nw_connection that we store in a address -> connection map.
+
+        Whenever sending a packet, we look at the remote address.
+        If needed, we create a nw_connection to that particular remote address and store it in the address -> connection map.
+        We then use the pre-existing or newly created nw_connection to send the packet.
+
+        Make sure to cancel NW connection in case of failure before releasing the socket.
+
+        Covered by existing tests
+
+        * NetworkProcess/webrtc/NetworkRTCProvider.cpp:
+        (WebKit::NetworkRTCProvider::createUDPSocket):
+        (WebKit::NetworkRTCProvider::createClientTCPSocket):
+        * NetworkProcess/webrtc/NetworkRTCProvider.h:
+        (WebKit::NetworkRTCProvider::setPlatformTCPSocketsEnabled):
+        (WebKit::NetworkRTCProvider::setPlatformUDPSocketsEnabled):
+        * NetworkProcess/webrtc/NetworkRTCProvider.messages.in:
+        * NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.h: Copied from Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h.
+        * NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.mm: Renamed from Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm.
+        (WebKit::tcpSocketQueue):
+        (WebKit::NetworkRTCTCPSocketCocoa::createClientTCPSocket):
+        (WebKit::NetworkRTCTCPSocketCocoa::NetworkRTCTCPSocketCocoa):
+        (WebKit::NetworkRTCTCPSocketCocoa::close):
+        (WebKit::NetworkRTCTCPSocketCocoa::setOption):
+        (WebKit::NetworkRTCTCPSocketCocoa::createMessageBuffer):
+        (WebKit::NetworkRTCTCPSocketCocoa::sendTo):
+        * NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.h: Added.
+        (WTF::DefaultHash<rtc::SocketAddress>::hash):
+        (WTF::DefaultHash<rtc::SocketAddress>::equal):
+        (WTF::HashTraits<rtc::SocketAddress>::emptyValue):
+        (WTF::HashTraits<rtc::SocketAddress>::constructDeletedValue):
+        (WTF::HashTraits<rtc::SocketAddress>::isDeletedValue):
+        * NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.mm: Added.
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::create):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::WTF_GUARDED_BY_LOCK):
+        (WebKit::udpSocketQueue):
+        (WebKit::NetworkRTCUDPSocketCocoa::createUDPSocket):
+        (WebKit::NetworkRTCUDPSocketCocoa::NetworkRTCUDPSocketCocoa):
+        (WebKit::NetworkRTCUDPSocketCocoa::~NetworkRTCUDPSocketCocoa):
+        (WebKit::NetworkRTCUDPSocketCocoa::close):
+        (WebKit::NetworkRTCUDPSocketCocoa::setOption):
+        (WebKit::NetworkRTCUDPSocketCocoa::sendTo):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::NetworkRTCUDPSocketCocoaConnections):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::close):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::setOption):
+        (WebKit::processUDPData):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::createNWConnection):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::setupNWConnection):
+        (WebKit::NetworkRTCUDPSocketCocoaConnections::sendTo):
+        * SourcesCocoa.txt:
+        * WebKit.xcodeproj/project.pbxproj:
+        * WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp:
+        (WebKit::LibWebRTCSocketFactory::setConnection):
+
 2021-07-01  Carlos Garcia Campos  <cgar...@igalia.com>
 
         [Cairo] Simplify GraphicsContextCairo creation

Modified: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.cpp (279460 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.cpp	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.cpp	2021-07-01 10:37:39 UTC (rev 279461)
@@ -46,7 +46,8 @@
 
 #if PLATFORM(COCOA)
 #include "NetworkRTCResolverCocoa.h"
-#include "NetworkRTCSocketCocoa.h"
+#include "NetworkRTCTCPSocketCocoa.h"
+#include "NetworkRTCUDPSocketCocoa.h"
 #endif
 
 namespace WebKit {
@@ -133,6 +134,15 @@
 
 void NetworkRTCProvider::createUDPSocket(LibWebRTCSocketIdentifier identifier, const RTCNetwork::SocketAddress& address, uint16_t minPort, uint16_t maxPort)
 {
+#if PLATFORM(COCOA)
+    if (m_platformUDPSocketsEnabled) {
+        if (auto socket = NetworkRTCUDPSocketCocoa::createUDPSocket(identifier, *this, address.value, minPort, maxPort, m_ipcConnection.copyRef())) {
+            addSocket(identifier, WTFMove(socket));
+            return;
+        }
+    }
+#endif
+
     ASSERT(m_rtcNetworkThread.IsCurrent());
     std::unique_ptr<rtc::AsyncPacketSocket> socket(m_packetSocketFactory->CreateUdpSocket(address.value, minPort, maxPort));
     createSocket(identifier, WTFMove(socket), Socket::Type::UDP, m_ipcConnection.copyRef());
@@ -177,8 +187,8 @@
         }
         callOnRTCNetworkThread([this, identifier, localAddress = RTCNetwork::isolatedCopy(localAddress.value), remoteAddress = RTCNetwork::isolatedCopy(remoteAddress.value), proxyInfo = proxyInfoFromSession(remoteAddress, *session), userAgent = WTFMove(userAgent).isolatedCopy(), options]() mutable {
 #if PLATFORM(COCOA)
-            if (m_platformSocketsEnabled) {
-                if (auto socket = NetworkRTCSocketCocoa::createClientTCPSocket(identifier, *this, remoteAddress, options, m_ipcConnection.copyRef())) {
+            if (m_platformTCPSocketsEnabled) {
+                if (auto socket = NetworkRTCTCPSocketCocoa::createClientTCPSocket(identifier, *this, remoteAddress, options, m_ipcConnection.copyRef())) {
                     addSocket(identifier, WTFMove(socket));
                     return;
                 }

Modified: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.h (279460 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.h	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.h	2021-07-01 10:37:39 UTC (rev 279461)
@@ -101,6 +101,8 @@
 
     IPC::Connection& connection() { return m_ipcConnection.get(); }
 
+    void closeSocket(WebCore::LibWebRTCSocketIdentifier);
+
 private:
     explicit NetworkRTCProvider(NetworkConnectionToWebProcess&);
     void startListeningForIPC();
@@ -110,9 +112,9 @@
     void createServerTCPSocket(WebCore::LibWebRTCSocketIdentifier, const RTCNetwork::SocketAddress&, uint16_t minPort, uint16_t maxPort, int);
     void wrapNewTCPConnection(WebCore::LibWebRTCSocketIdentifier identifier, WebCore::LibWebRTCSocketIdentifier newConnectionSocketIdentifier);
     void sendToSocket(WebCore::LibWebRTCSocketIdentifier, const IPC::DataReference&, RTCNetwork::SocketAddress&&, RTCPacketOptions&&);
-    void closeSocket(WebCore::LibWebRTCSocketIdentifier);
     void setSocketOption(WebCore::LibWebRTCSocketIdentifier, int option, int value);
-    void setPlatformSocketsEnabled(bool enabled) { m_platformSocketsEnabled = enabled; }
+    void setPlatformTCPSocketsEnabled(bool enabled) { m_platformTCPSocketsEnabled = enabled; }
+    void setPlatformUDPSocketsEnabled(bool enabled) { m_platformUDPSocketsEnabled = enabled; }
 
     void createResolver(LibWebRTCResolverIdentifier, String&&);
     void stopResolver(LibWebRTCResolverIdentifier);
@@ -141,7 +143,8 @@
 
     HashMap<WebCore::LibWebRTCSocketIdentifier, std::unique_ptr<rtc::AsyncPacketSocket>> m_pendingIncomingSockets;
     bool m_isListeningSocketAuthorized { true };
-    bool m_platformSocketsEnabled { false };
+    bool m_platformTCPSocketsEnabled { false };
+    bool m_platformUDPSocketsEnabled { false };
 };
 
 } // namespace WebKit

Modified: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.messages.in (279460 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.messages.in	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.messages.in	2021-07-01 10:37:39 UTC (rev 279461)
@@ -28,7 +28,8 @@
     CreateClientTCPSocket(WebCore::LibWebRTCSocketIdentifier identifier, WebKit::RTCNetwork::SocketAddress localAddress, WebKit::RTCNetwork::SocketAddress remoteAddress, String userAgent, int options)
     WrapNewTCPConnection(WebCore::LibWebRTCSocketIdentifier identifier, WebCore::LibWebRTCSocketIdentifier newConnectionSocketIdentifier)
 
-    void SetPlatformSocketsEnabled(bool enabled)
+    void SetPlatformTCPSocketsEnabled(bool enabled)
+    void SetPlatformUDPSocketsEnabled(bool enabled)
 
     CreateResolver(WebKit::LibWebRTCResolverIdentifier identifier, String address)
     StopResolver(WebKit::LibWebRTCResolverIdentifier identifier)

Deleted: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h (279460 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2020 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
-
-#if USE(LIBWEBRTC) && PLATFORM(COCOA)
-
-#include "NetworkRTCProvider.h"
-#include <Network/Network.h>
-
-namespace rtc {
-class SocketAddress;
-}
-
-namespace WebKit {
-
-class NetworkRTCSocketCocoa final : public NetworkRTCProvider::Socket {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    static std::unique_ptr<NetworkRTCProvider::Socket> createClientTCPSocket(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, int options, Ref<IPC::Connection>&&);
-
-    NetworkRTCSocketCocoa(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, int options, Ref<IPC::Connection>&&);
-
-private:
-    // NetworkRTCProvider::Socket.
-    WebCore::LibWebRTCSocketIdentifier identifier() const final { return m_identifier; }
-    Type type() const final { return Type::ClientTCP; }
-    void close() final;
-    void setOption(int option, int value) final;
-    void sendTo(const uint8_t*, size_t, const rtc::SocketAddress&, const rtc::PacketOptions&) final;
-
-    Vector<uint8_t> createMessageBuffer(const uint8_t*, size_t);
-
-    WebCore::LibWebRTCSocketIdentifier m_identifier;
-    NetworkRTCProvider& m_rtcProvider;
-    Ref<IPC::Connection> m_connection;
-    RetainPtr<nw_connection_t> m_nwConnection;
-    bool m_isSTUN { false };
-};
-
-} // namespace WebKit
-
-#endif // USE(LIBWEBRTC) && PLATFORM(COCOA)

Deleted: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm (279460 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm	2021-07-01 10:37:39 UTC (rev 279461)
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2020 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 "NetworkRTCSocketCocoa.h"
-
-#if USE(LIBWEBRTC) && PLATFORM(COCOA)
-
-#include "DataReference.h"
-#include "LibWebRTCNetworkMessages.h"
-#include <WebCore/STUNMessageParsing.h>
-#include <dispatch/dispatch.h>
-#include <wtf/BlockPtr.h>
-
-namespace WebKit {
-
-using namespace WebCore;
-
-static dispatch_queue_t socketQueue()
-{
-    static dispatch_queue_t queue;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        queue = dispatch_queue_create("WebRTC socket queue", DISPATCH_QUEUE_CONCURRENT);
-    });
-    return queue;
-}
-
-std::unique_ptr<NetworkRTCProvider::Socket> NetworkRTCSocketCocoa::createClientTCPSocket(LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& remoteAddress, int tcpOptions, Ref<IPC::Connection>&& connection)
-{
-    // FIXME: We should migrate ssltcp candidates, maybe support OPT_TLS_INSECURE as well.
-    if ((tcpOptions & rtc::PacketSocketFactory::OPT_TLS_FAKE) || (tcpOptions & rtc::PacketSocketFactory::OPT_TLS_INSECURE))
-        return nullptr;
-    return makeUnique<NetworkRTCSocketCocoa>(identifier, rtcProvider, remoteAddress, tcpOptions, WTFMove(connection));
-}
-
-static inline void processIncomingData(RetainPtr<nw_connection_t>&& nwConnection, Function<Vector<uint8_t>(Vector<uint8_t>&&)>&& processData, Vector<uint8_t>&& buffer = { })
-{
-    auto nwConnectionReference = nwConnection.get();
-    nw_connection_receive(nwConnectionReference, 1, std::numeric_limits<uint32_t>::max(), makeBlockPtr([nwConnection = WTFMove(nwConnection), processData = WTFMove(processData), buffer = WTFMove(buffer)](dispatch_data_t content, nw_content_context_t context, bool isComplete, nw_error_t error) mutable {
-        if (content) {
-            dispatch_data_apply(content, makeBlockPtr([&](dispatch_data_t, size_t, const void* data, size_t size) {
-                // FIXME: Introduce uncheckedAppend version.
-                buffer.append(static_cast<const uint8_t*>(data), size);
-                return true;
-            }).get());
-            buffer = processData(WTFMove(buffer));
-        }
-        if (isComplete && context && nw_content_context_get_is_final(context))
-            return;
-        if (error)
-            return;
-        processIncomingData(WTFMove(nwConnection), WTFMove(processData), WTFMove(buffer));
-    }).get());
-}
-
-NetworkRTCSocketCocoa::NetworkRTCSocketCocoa(LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& remoteAddress, int options, Ref<IPC::Connection>&& connection)
-    : m_identifier(identifier)
-    , m_rtcProvider(rtcProvider)
-    , m_connection(WTFMove(connection))
-    , m_isSTUN(options & rtc::PacketSocketFactory::OPT_STUN)
-{
-    auto hostName = remoteAddress.hostname();
-    if (hostName.empty())
-        hostName = remoteAddress.ipaddr().ToString();
-    auto host = adoptNS(nw_endpoint_create_host(hostName.c_str(), String::number(remoteAddress.port()).utf8().data()));
-    // FIXME: Handle TLS certificate validation like for other network code paths, using sec_protocol_options_set_verify_block
-    bool isTLS = options & rtc::PacketSocketFactory::OPT_TLS;
-    auto tcpTLS = adoptNS(nw_parameters_create_secure_tcp(isTLS ? NW_PARAMETERS_DEFAULT_CONFIGURATION : NW_PARAMETERS_DISABLE_PROTOCOL, ^(nw_protocol_options_t tcp_options) {
-        nw_tcp_options_set_no_delay(tcp_options, true);
-    }));
-
-    m_nwConnection = adoptNS(nw_connection_create(host.get(), tcpTLS.get()));
-
-    nw_connection_set_queue(m_nwConnection.get(), socketQueue());
-    nw_connection_set_state_changed_handler(m_nwConnection.get(), makeBlockPtr([identifier = m_identifier, rtcProvider = makeRef(rtcProvider), connection = m_connection.copyRef()](nw_connection_state_t state, _Nullable nw_error_t error) {
-        ASSERT_UNUSED(error, !error);
-        switch (state) {
-        case nw_connection_state_invalid:
-        case nw_connection_state_waiting:
-        case nw_connection_state_preparing:
-            return;
-        case nw_connection_state_ready:
-            connection->send(Messages::LibWebRTCNetwork::SignalConnect(identifier), 0);
-            return;
-        case nw_connection_state_failed:
-            rtcProvider->callOnRTCNetworkThread([rtcProvider, identifier] {
-                rtcProvider->takeSocket(identifier);
-            });
-            connection->send(Messages::LibWebRTCNetwork::SignalClose(identifier, -1), 0);
-            return;
-        case nw_connection_state_cancelled:
-            return;
-        }
-    }).get());
-
-    processIncomingData(m_nwConnection.get(), [identifier = m_identifier, connection = m_connection.copyRef(), ip = remoteAddress.ipaddr(), port = remoteAddress.port(), isSTUN = m_isSTUN](auto&& buffer) mutable {
-        return WebRTC::extractMessages(WTFMove(buffer), isSTUN ? WebRTC::MessageType::STUN : WebRTC::MessageType::Data, [&](auto* message, auto size) {
-            IPC::DataReference data(message, size);
-            connection->send(Messages::LibWebRTCNetwork::SignalReadPacket { identifier, data, RTCNetwork::IPAddress(ip), port, rtc::TimeMillis() * 1000 }, 0);
-        });
-    });
-
-    nw_connection_start(m_nwConnection.get());
-}
-
-void NetworkRTCSocketCocoa::close()
-{
-    if (!m_nwConnection)
-        return;
-    nw_connection_cancel(m_nwConnection.get());
-    m_rtcProvider.takeSocket(m_identifier);
-}
-
-void NetworkRTCSocketCocoa::setOption(int, int)
-{
-    // FIXME: Validate this is not needed.
-}
-
-static RetainPtr<dispatch_data_t> dataFromVector(Vector<uint8_t>&& v)
-{
-    auto bufferSize = v.size();
-    auto rawPointer = v.releaseBuffer().leakPtr();
-    return adoptNS(dispatch_data_create(rawPointer, bufferSize, dispatch_get_main_queue(), ^{
-        fastFree(rawPointer);
-    }));
-}
-
-Vector<uint8_t> NetworkRTCSocketCocoa::createMessageBuffer(const uint8_t* data, size_t size)
-{
-    if (size >= std::numeric_limits<uint16_t>::max())
-        return { };
-
-    if (m_isSTUN) {
-        auto messageLengths = WebRTC::getSTUNOrTURNMessageLengths(data, size);
-        if (!messageLengths)
-            return { };
-
-        ASSERT(messageLengths->messageLength == size);
-        ASSERT(messageLengths->messageLengthWithPadding >= size);
-        if (messageLengths->messageLengthWithPadding < size)
-            return { };
-
-        Vector<uint8_t> buffer;
-        buffer.reserveInitialCapacity(messageLengths->messageLengthWithPadding);
-        buffer.append(data, size);
-        for (size_t cptr = 0 ; cptr < messageLengths->messageLengthWithPadding - size; ++cptr)
-            buffer.uncheckedAppend(0);
-        return buffer;
-    }
-
-    // Prepend length.
-    Vector<uint8_t> buffer;
-    buffer.reserveInitialCapacity(size + 2);
-    buffer.uncheckedAppend((size >> 8) & 0xFF);
-    buffer.uncheckedAppend(size & 0xFF);
-    buffer.append(data, size);
-    return buffer;
-}
-
-void NetworkRTCSocketCocoa::sendTo(const uint8_t* data, size_t size, const rtc::SocketAddress&, const rtc::PacketOptions& options)
-{
-    auto buffer = createMessageBuffer(data, size);
-    if (buffer.isEmpty())
-        return;
-
-    nw_connection_send(m_nwConnection.get(), dataFromVector(WTFMove(buffer)).get(), NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, makeBlockPtr([identifier = m_identifier, connection = m_connection.copyRef(), options](_Nullable nw_error_t) {
-        connection->send(Messages::LibWebRTCNetwork::SignalSentPacket { identifier, options.packet_id, rtc::TimeMillis() }, 0);
-    }).get());
-}
-
-} // namespace WebKit
-
-#endif // USE(LIBWEBRTC) && PLATFORM(COCOA)

Copied: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.h (from rev 279460, trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h) (0 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.h	                        (rev 0)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.h	2021-07-01 10:37:39 UTC (rev 279461)
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2020-2021 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
+
+#if USE(LIBWEBRTC) && PLATFORM(COCOA)
+
+#include "NetworkRTCProvider.h"
+#include <Network/Network.h>
+
+namespace rtc {
+class SocketAddress;
+}
+
+namespace WebKit {
+
+class NetworkRTCTCPSocketCocoa final : public NetworkRTCProvider::Socket {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    static std::unique_ptr<NetworkRTCProvider::Socket> createClientTCPSocket(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, int options, Ref<IPC::Connection>&&);
+
+    NetworkRTCTCPSocketCocoa(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, int options, Ref<IPC::Connection>&&);
+
+private:
+    // NetworkRTCProvider::Socket.
+    WebCore::LibWebRTCSocketIdentifier identifier() const final { return m_identifier; }
+    Type type() const final { return Type::ClientTCP; }
+    void close() final;
+    void setOption(int option, int value) final;
+    void sendTo(const uint8_t*, size_t, const rtc::SocketAddress&, const rtc::PacketOptions&) final;
+
+    Vector<uint8_t> createMessageBuffer(const uint8_t*, size_t);
+
+    WebCore::LibWebRTCSocketIdentifier m_identifier;
+    NetworkRTCProvider& m_rtcProvider;
+    Ref<IPC::Connection> m_connection;
+    RetainPtr<nw_connection_t> m_nwConnection;
+    bool m_isSTUN { false };
+};
+
+} // namespace WebKit
+
+#endif // USE(LIBWEBRTC) && PLATFORM(COCOA)

Copied: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.mm (from rev 279460, trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm) (0 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.mm	                        (rev 0)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.mm	2021-07-01 10:37:39 UTC (rev 279461)
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2020-2021 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 "NetworkRTCTCPSocketCocoa.h"
+
+#if USE(LIBWEBRTC) && PLATFORM(COCOA)
+
+#include "DataReference.h"
+#include "LibWebRTCNetworkMessages.h"
+#include "Logging.h"
+#include <WebCore/STUNMessageParsing.h>
+#include <dispatch/dispatch.h>
+#include <wtf/BlockPtr.h>
+
+namespace WebKit {
+
+using namespace WebCore;
+
+static dispatch_queue_t tcpSocketQueue()
+{
+    static dispatch_queue_t queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        queue = dispatch_queue_create("WebRTC TCP socket queue", DISPATCH_QUEUE_CONCURRENT);
+    });
+    return queue;
+}
+
+std::unique_ptr<NetworkRTCProvider::Socket> NetworkRTCTCPSocketCocoa::createClientTCPSocket(LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& remoteAddress, int tcpOptions, Ref<IPC::Connection>&& connection)
+{
+    // FIXME: We should migrate ssltcp candidates, maybe support OPT_TLS_INSECURE as well.
+    if ((tcpOptions & rtc::PacketSocketFactory::OPT_TLS_FAKE) || (tcpOptions & rtc::PacketSocketFactory::OPT_TLS_INSECURE))
+        return nullptr;
+    return makeUnique<NetworkRTCTCPSocketCocoa>(identifier, rtcProvider, remoteAddress, tcpOptions, WTFMove(connection));
+}
+
+static inline void processIncomingData(RetainPtr<nw_connection_t>&& nwConnection, Function<Vector<uint8_t>(Vector<uint8_t>&&)>&& processData, Vector<uint8_t>&& buffer = { })
+{
+    auto nwConnectionReference = nwConnection.get();
+    nw_connection_receive(nwConnectionReference, 1, std::numeric_limits<uint32_t>::max(), makeBlockPtr([nwConnection = WTFMove(nwConnection), processData = WTFMove(processData), buffer = WTFMove(buffer)](dispatch_data_t content, nw_content_context_t context, bool isComplete, nw_error_t error) mutable {
+        if (content) {
+            dispatch_data_apply(content, makeBlockPtr([&](dispatch_data_t, size_t, const void* data, size_t size) {
+                // FIXME: Introduce uncheckedAppend version.
+                buffer.append(static_cast<const uint8_t*>(data), size);
+                return true;
+            }).get());
+            buffer = processData(WTFMove(buffer));
+        }
+        if (isComplete && context && nw_content_context_get_is_final(context))
+            return;
+        if (error) {
+            RELEASE_LOG_ERROR(WebRTC, "NetworkRTCTCPSocketCocoa processIncomingData failed with error %d", nw_error_get_error_code(error));
+            return;
+        }
+        processIncomingData(WTFMove(nwConnection), WTFMove(processData), WTFMove(buffer));
+    }).get());
+}
+
+NetworkRTCTCPSocketCocoa::NetworkRTCTCPSocketCocoa(LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& remoteAddress, int options, Ref<IPC::Connection>&& connection)
+    : m_identifier(identifier)
+    , m_rtcProvider(rtcProvider)
+    , m_connection(WTFMove(connection))
+    , m_isSTUN(options & rtc::PacketSocketFactory::OPT_STUN)
+{
+    auto hostName = remoteAddress.hostname();
+    if (hostName.empty())
+        hostName = remoteAddress.ipaddr().ToString();
+    auto host = adoptNS(nw_endpoint_create_host(hostName.c_str(), String::number(remoteAddress.port()).utf8().data()));
+    // FIXME: Handle TLS certificate validation like for other network code paths, using sec_protocol_options_set_verify_block
+    bool isTLS = options & rtc::PacketSocketFactory::OPT_TLS;
+    auto tcpTLS = adoptNS(nw_parameters_create_secure_tcp(isTLS ? NW_PARAMETERS_DEFAULT_CONFIGURATION : NW_PARAMETERS_DISABLE_PROTOCOL, ^(nw_protocol_options_t tcp_options) {
+        nw_tcp_options_set_no_delay(tcp_options, true);
+    }));
+
+    m_nwConnection = adoptNS(nw_connection_create(host.get(), tcpTLS.get()));
+
+    nw_connection_set_queue(m_nwConnection.get(), tcpSocketQueue());
+    nw_connection_set_state_changed_handler(m_nwConnection.get(), makeBlockPtr([identifier = m_identifier, rtcProvider = makeRef(rtcProvider), connection = m_connection.copyRef()](nw_connection_state_t state, _Nullable nw_error_t error) {
+        ASSERT_UNUSED(error, !error);
+        switch (state) {
+        case nw_connection_state_invalid:
+        case nw_connection_state_waiting:
+        case nw_connection_state_preparing:
+            return;
+        case nw_connection_state_ready:
+            connection->send(Messages::LibWebRTCNetwork::SignalConnect(identifier), 0);
+            return;
+        case nw_connection_state_failed:
+            rtcProvider->callOnRTCNetworkThread([rtcProvider, identifier] {
+                rtcProvider->closeSocket(identifier);
+            });
+            connection->send(Messages::LibWebRTCNetwork::SignalClose(identifier, -1), 0);
+            return;
+        case nw_connection_state_cancelled:
+            return;
+        }
+    }).get());
+
+    processIncomingData(m_nwConnection.get(), [identifier = m_identifier, connection = m_connection.copyRef(), ip = remoteAddress.ipaddr(), port = remoteAddress.port(), isSTUN = m_isSTUN](auto&& buffer) mutable {
+        return WebRTC::extractMessages(WTFMove(buffer), isSTUN ? WebRTC::MessageType::STUN : WebRTC::MessageType::Data, [&](auto* message, auto size) {
+            IPC::DataReference data(message, size);
+            connection->send(Messages::LibWebRTCNetwork::SignalReadPacket { identifier, data, RTCNetwork::IPAddress(ip), port, rtc::TimeMillis() * 1000 }, 0);
+        });
+    });
+
+    nw_connection_start(m_nwConnection.get());
+}
+
+void NetworkRTCTCPSocketCocoa::close()
+{
+    if (!m_nwConnection)
+        return;
+    nw_connection_cancel(m_nwConnection.get());
+    m_rtcProvider.takeSocket(m_identifier);
+}
+
+void NetworkRTCTCPSocketCocoa::setOption(int, int)
+{
+    // FIXME: Validate this is not needed.
+}
+
+static RetainPtr<dispatch_data_t> dataFromVector(Vector<uint8_t>&& v)
+{
+    auto bufferSize = v.size();
+    auto rawPointer = v.releaseBuffer().leakPtr();
+    return adoptNS(dispatch_data_create(rawPointer, bufferSize, dispatch_get_main_queue(), ^{
+        fastFree(rawPointer);
+    }));
+}
+
+Vector<uint8_t> NetworkRTCTCPSocketCocoa::createMessageBuffer(const uint8_t* data, size_t size)
+{
+    if (size >= std::numeric_limits<uint16_t>::max())
+        return { };
+
+    if (m_isSTUN) {
+        auto messageLengths = WebRTC::getSTUNOrTURNMessageLengths(data, size);
+        if (!messageLengths)
+            return { };
+
+        ASSERT(messageLengths->messageLength == size);
+        ASSERT(messageLengths->messageLengthWithPadding >= size);
+        if (messageLengths->messageLengthWithPadding < size)
+            return { };
+
+        Vector<uint8_t> buffer;
+        buffer.reserveInitialCapacity(messageLengths->messageLengthWithPadding);
+        buffer.append(data, size);
+        for (size_t cptr = 0 ; cptr < messageLengths->messageLengthWithPadding - size; ++cptr)
+            buffer.uncheckedAppend(0);
+        return buffer;
+    }
+
+    // Prepend length.
+    Vector<uint8_t> buffer;
+    buffer.reserveInitialCapacity(size + 2);
+    buffer.uncheckedAppend((size >> 8) & 0xFF);
+    buffer.uncheckedAppend(size & 0xFF);
+    buffer.append(data, size);
+    return buffer;
+}
+
+void NetworkRTCTCPSocketCocoa::sendTo(const uint8_t* data, size_t size, const rtc::SocketAddress&, const rtc::PacketOptions& options)
+{
+    auto buffer = createMessageBuffer(data, size);
+    if (buffer.isEmpty())
+        return;
+
+    nw_connection_send(m_nwConnection.get(), dataFromVector(WTFMove(buffer)).get(), NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, makeBlockPtr([identifier = m_identifier, connection = m_connection.copyRef(), options](_Nullable nw_error_t) {
+        connection->send(Messages::LibWebRTCNetwork::SignalSentPacket { identifier, options.packet_id, rtc::TimeMillis() }, 0);
+    }).get());
+}
+
+} // namespace WebKit
+
+#endif // USE(LIBWEBRTC) && PLATFORM(COCOA)

Copied: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.h (from rev 279460, trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCSocketCocoa.h) (0 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.h	                        (rev 0)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.h	2021-07-01 10:37:39 UTC (rev 279461)
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2021 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
+
+#if USE(LIBWEBRTC) && PLATFORM(COCOA)
+
+#include "NetworkRTCProvider.h"
+#include <Network/Network.h>
+#include <wtf/HashMap.h>
+#include <wtf/Lock.h>
+
+namespace rtc {
+class SocketAddress;
+}
+
+namespace WTF {
+
+template<> struct DefaultHash<rtc::SocketAddress> {
+    static unsigned hash(const rtc::SocketAddress& address) { return address.Hash(); }
+    static bool equal(const rtc::SocketAddress& a, const rtc::SocketAddress& b) { return a == b || (a.IsNil() && b.IsNil() && a.scope_id() == b.scope_id()); }
+    static constexpr bool safeToCompareToEmptyOrDeleted = true;
+};
+
+template<> struct HashTraits<rtc::SocketAddress> : GenericHashTraits<rtc::SocketAddress> {
+    static rtc::SocketAddress emptyValue() { return rtc::SocketAddress { }; }
+    static void constructDeletedValue(rtc::SocketAddress& address) { address = { }; address.SetScopeID(-1); }
+    static bool isDeletedValue(const rtc::SocketAddress& address) { return address.scope_id() == -1; }
+};
+
+}
+
+namespace WebKit {
+
+class NetworkRTCUDPSocketCocoaConnections;
+
+class NetworkRTCUDPSocketCocoa final : public NetworkRTCProvider::Socket {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    static std::unique_ptr<NetworkRTCProvider::Socket> createUDPSocket(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, uint16_t minPort, uint16_t maxPort, Ref<IPC::Connection>&&);
+
+    NetworkRTCUDPSocketCocoa(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, Ref<IPC::Connection>&&);
+    ~NetworkRTCUDPSocketCocoa();
+
+private:
+    // NetworkRTCProvider::Socket.
+    WebCore::LibWebRTCSocketIdentifier identifier() const final { return m_identifier; }
+    Type type() const final { return Type::UDP; }
+    void close() final;
+    void setOption(int option, int value) final;
+    void sendTo(const uint8_t*, size_t, const rtc::SocketAddress&, const rtc::PacketOptions&) final;
+
+    NetworkRTCProvider& m_rtcProvider;
+    WebCore::LibWebRTCSocketIdentifier m_identifier;
+    Ref<NetworkRTCUDPSocketCocoaConnections> m_nwConnections;
+};
+
+} // namespace WebKit
+
+#endif // USE(LIBWEBRTC) && PLATFORM(COCOA)

Added: trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.mm (0 => 279461)


--- trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.mm	                        (rev 0)
+++ trunk/Source/WebKit/NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.mm	2021-07-01 10:37:39 UTC (rev 279461)
@@ -0,0 +1,272 @@
+/*
+ * Copyright (C) 2021 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 "NetworkRTCUDPSocketCocoa.h"
+
+#if USE(LIBWEBRTC) && PLATFORM(COCOA)
+
+#include "DataReference.h"
+#include "LibWebRTCNetworkMessages.h"
+#include "Logging.h"
+#include <WebCore/STUNMessageParsing.h>
+#include <dispatch/dispatch.h>
+#include <wtf/BlockPtr.h>
+#include <wtf/ThreadSafeRefCounted.h>
+
+namespace WebKit {
+
+using namespace WebCore;
+
+class NetworkRTCUDPSocketCocoaConnections : public ThreadSafeRefCounted<NetworkRTCUDPSocketCocoaConnections> {
+public:
+    static Ref<NetworkRTCUDPSocketCocoaConnections> create(WebCore::LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& provider, const rtc::SocketAddress& address, Ref<IPC::Connection>&& connection) { return adoptRef(*new NetworkRTCUDPSocketCocoaConnections(identifier, provider, address, WTFMove(connection))); }
+
+    void close();
+    void setOption(int option, int value);
+    void sendTo(const uint8_t*, size_t, const rtc::SocketAddress&, const rtc::PacketOptions&);
+
+private:
+    NetworkRTCUDPSocketCocoaConnections(WebCore::LibWebRTCSocketIdentifier, NetworkRTCProvider&, const rtc::SocketAddress&, Ref<IPC::Connection>&&);
+
+    RetainPtr<nw_connection_t> createNWConnection(const rtc::SocketAddress&);
+    void setupNWConnection(nw_connection_t, const rtc::SocketAddress&);
+
+    WebCore::LibWebRTCSocketIdentifier m_identifier;
+    Ref<IPC::Connection> m_connection;
+    rtc::SocketAddress m_address;
+    RetainPtr<nw_listener_t> m_nwListener;
+    Lock m_nwConnectionsLock;
+    bool m_isClosed WTF_GUARDED_BY_LOCK(m_nwConnectionsLock) { false };
+    HashMap<rtc::SocketAddress, RetainPtr<nw_connection_t>> m_nwConnections WTF_GUARDED_BY_LOCK(m_nwConnectionsLock);
+};
+
+static dispatch_queue_t udpSocketQueue()
+{
+    static dispatch_queue_t queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        queue = dispatch_queue_create("WebRTC UDP socket queue", DISPATCH_QUEUE_CONCURRENT);
+    });
+    return queue;
+}
+
+std::unique_ptr<NetworkRTCProvider::Socket> NetworkRTCUDPSocketCocoa::createUDPSocket(WebCore::LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort, Ref<IPC::Connection>&& connection)
+{
+    // FIXME: Decide how to use minPort/maxPort.
+    return makeUnique<NetworkRTCUDPSocketCocoa>(identifier, rtcProvider, address, WTFMove(connection));
+}
+
+NetworkRTCUDPSocketCocoa::NetworkRTCUDPSocketCocoa(WebCore::LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& address, Ref<IPC::Connection>&& connection)
+    : m_rtcProvider(rtcProvider)
+    , m_identifier(identifier)
+    , m_nwConnections(NetworkRTCUDPSocketCocoaConnections::create(identifier, rtcProvider, address, WTFMove(connection)))
+{
+}
+
+NetworkRTCUDPSocketCocoa::~NetworkRTCUDPSocketCocoa()
+{
+}
+
+void NetworkRTCUDPSocketCocoa::close()
+{
+    m_nwConnections->close();
+    m_rtcProvider.takeSocket(m_identifier);
+}
+
+void NetworkRTCUDPSocketCocoa::setOption(int option, int value)
+{
+    m_nwConnections->setOption(option, value);
+}
+
+void NetworkRTCUDPSocketCocoa::sendTo(const uint8_t* data, size_t size, const rtc::SocketAddress& address, const rtc::PacketOptions& options)
+{
+    m_nwConnections->sendTo(data, size, address, options);
+}
+
+static rtc::SocketAddress socketAddressFromIncomingConnection(nw_connection_t connection)
+{
+    auto endpoint = adoptNS(nw_connection_copy_endpoint(connection));
+    auto type = nw_endpoint_get_type(endpoint.get());
+    if (type == nw_endpoint_type_address) {
+        auto* ipAddress = nw_endpoint_copy_address_string(endpoint.get());
+        rtc::SocketAddress remoteAddress { ipAddress, nw_endpoint_get_port(endpoint.get()) };
+        free(ipAddress);
+        return remoteAddress;
+    }
+    return rtc::SocketAddress { nw_endpoint_get_hostname(endpoint.get()), nw_endpoint_get_port(endpoint.get()) };
+}
+
+NetworkRTCUDPSocketCocoaConnections::NetworkRTCUDPSocketCocoaConnections(WebCore::LibWebRTCSocketIdentifier identifier, NetworkRTCProvider& rtcProvider, const rtc::SocketAddress& address, Ref<IPC::Connection>&& connection)
+    : m_identifier(identifier)
+    , m_connection(WTFMove(connection))
+{
+    auto parameters = adoptNS(nw_parameters_create_secure_udp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION));
+    {
+        auto hostAddress = address.ipaddr().ToString();
+        if (address.ipaddr().IsNil())
+            hostAddress = address.hostname();
+        auto localEndpoint = adoptNS(nw_endpoint_create_host(hostAddress.c_str(), "0"));
+        m_address = { nw_endpoint_get_hostname(localEndpoint.get()), nw_endpoint_get_port(localEndpoint.get()) };
+        nw_parameters_set_local_endpoint(parameters.get(), localEndpoint.get());
+    }
+    {
+        auto protocolStack = adoptNS(nw_parameters_copy_default_protocol_stack(parameters.get()));
+        auto options = adoptNS(nw_protocol_stack_copy_internet_protocol(protocolStack.get()));
+        nw_ip_options_set_version(options.get(), address.family() == AF_INET ? nw_ip_version_4 : nw_ip_version_6);
+    }
+
+    m_nwListener = adoptNS(nw_listener_create(parameters.get()));
+    nw_listener_set_queue(m_nwListener.get(), udpSocketQueue());
+
+    nw_listener_set_state_changed_handler(m_nwListener.get(), makeBlockPtr([nwListener = m_nwListener.get(), address = m_address, connection = m_connection.copyRef(), protectedRTCProvider = makeRef(rtcProvider), identifier = m_identifier](nw_listener_state_t state, nw_error_t error) mutable {
+        switch (state) {
+        case nw_listener_state_invalid:
+        case nw_listener_state_waiting:
+            break;
+        case nw_listener_state_ready:
+            address.SetPort(nw_listener_get_port(nwListener));
+            connection->send(Messages::LibWebRTCNetwork::SignalAddressReady(identifier, RTCNetwork::SocketAddress(address)), 0);
+            break;
+        case nw_listener_state_failed:
+            RELEASE_LOG_ERROR(WebRTC, "NetworkRTCUDPSocketCocoaConnections failed with error %d", error ? nw_error_get_error_code(error) : 0);
+            protectedRTCProvider->callOnRTCNetworkThread([protectedRTCProvider, identifier] {
+                protectedRTCProvider->closeSocket(identifier);
+            });
+            connection->send(Messages::LibWebRTCNetwork::SignalClose(identifier, -1), 0);
+            break;
+        case nw_listener_state_cancelled:
+            break;
+        }
+    }).get());
+
+    nw_listener_set_new_connection_handler(m_nwListener.get(), makeBlockPtr([protectedThis = makeRef(*this)](nw_connection_t connection) {
+        Locker locker { protectedThis->m_nwConnectionsLock };
+        if (protectedThis->m_isClosed)
+            return;
+
+        auto remoteAddress = socketAddressFromIncomingConnection(connection);
+        protectedThis->m_nwConnections.set(remoteAddress, connection);
+        protectedThis->setupNWConnection(connection, remoteAddress);
+    }).get());
+
+    nw_listener_start(m_nwListener.get());
+}
+
+void NetworkRTCUDPSocketCocoaConnections::close()
+{
+    Locker locker { m_nwConnectionsLock };
+    m_isClosed = true;
+
+    nw_listener_cancel(m_nwListener.get());
+    m_nwListener = nullptr;
+
+    for (auto& nwConnection : m_nwConnections.values())
+        nw_connection_cancel(nwConnection.get());
+    m_nwConnections.clear();
+}
+
+void NetworkRTCUDPSocketCocoaConnections::setOption(int, int)
+{
+    // FIXME: Validate this is not needed.
+}
+
+static inline void processUDPData(RetainPtr<nw_connection_t>&& nwConnection, Function<void(const uint8_t*, size_t)>&& processData)
+{
+    auto nwConnectionReference = nwConnection.get();
+    nw_connection_receive(nwConnectionReference, 1, std::numeric_limits<uint32_t>::max(), makeBlockPtr([nwConnection = WTFMove(nwConnection), processData = WTFMove(processData)](dispatch_data_t content, nw_content_context_t context, bool isComplete, nw_error_t error) mutable {
+        if (content) {
+            dispatch_data_apply(content, makeBlockPtr([&](dispatch_data_t, size_t, const void* data, size_t size) {
+                processData(static_cast<const uint8_t*>(data), size);
+                return true;
+            }).get());
+        }
+        if (isComplete && context && nw_content_context_get_is_final(context))
+            return;
+        if (error) {
+            RELEASE_LOG_ERROR(WebRTC, "NetworkRTCUDPSocketCocoaConnections failed processing UDP data with error %d", error ? nw_error_get_error_code(error) : 0);
+            return;
+        }
+        processUDPData(WTFMove(nwConnection), WTFMove(processData));
+    }).get());
+}
+
+RetainPtr<nw_connection_t> NetworkRTCUDPSocketCocoaConnections::createNWConnection(const rtc::SocketAddress& remoteAddress)
+{
+    auto parameters = adoptNS(nw_parameters_create_secure_udp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION));
+    {
+        auto hostAddress = m_address.ipaddr().ToString();
+        if (m_address.ipaddr().IsNil())
+            hostAddress = m_address.hostname();
+        auto localEndpoint = adoptNS(nw_endpoint_create_host(hostAddress.c_str(), String::number(m_address.port()).utf8().data()));
+        nw_parameters_set_local_endpoint(parameters.get(), localEndpoint.get());
+    }
+    {
+        auto protocolStack = adoptNS(nw_parameters_copy_default_protocol_stack(parameters.get()));
+        auto options = adoptNS(nw_protocol_stack_copy_internet_protocol(protocolStack.get()));
+        nw_ip_options_set_version(options.get(), remoteAddress.family() == AF_INET ? nw_ip_version_4 : nw_ip_version_6);
+    }
+
+    auto remoteHostAddress = remoteAddress.ipaddr().ToString();
+    if (remoteAddress.ipaddr().IsNil())
+        remoteHostAddress = remoteAddress.hostname();
+    auto host = adoptNS(nw_endpoint_create_host(remoteHostAddress.c_str(), String::number(remoteAddress.port()).utf8().data()));
+    auto nwConnection = adoptNS(nw_connection_create(host.get(), parameters.get()));
+
+    setupNWConnection(nwConnection.get(), remoteAddress);
+    return nwConnection;
+}
+
+void NetworkRTCUDPSocketCocoaConnections::setupNWConnection(nw_connection_t nwConnection, const rtc::SocketAddress& remoteAddress)
+{
+    nw_connection_set_queue(nwConnection, udpSocketQueue());
+
+    processUDPData(nwConnection, [identifier = m_identifier, connection = m_connection.copyRef(), ip = remoteAddress.ipaddr(), port = remoteAddress.port()](auto* message, auto size) mutable {
+        IPC::DataReference data(message, size);
+        connection->send(Messages::LibWebRTCNetwork::SignalReadPacket { identifier, data, RTCNetwork::IPAddress(ip), port, rtc::TimeMillis() * 1000 }, 0);
+    });
+
+    nw_connection_start(nwConnection);
+}
+
+void NetworkRTCUDPSocketCocoaConnections::sendTo(const uint8_t* data, size_t size, const rtc::SocketAddress& remoteAddress, const rtc::PacketOptions& options)
+{
+    nw_connection_t nwConnection;
+    {
+        Locker locker { m_nwConnectionsLock };
+        nwConnection = m_nwConnections.ensure(remoteAddress, [this, &remoteAddress] {
+            return createNWConnection(remoteAddress);
+        }).iterator->value.get();
+    }
+
+    auto value = adoptNS(dispatch_data_create(data, size, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT));
+    nw_connection_send(nwConnection, value.get(), NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, makeBlockPtr([identifier = m_identifier, connection = m_connection.copyRef(), options](_Nullable nw_error_t) {
+        connection->send(Messages::LibWebRTCNetwork::SignalSentPacket { identifier, options.packet_id, rtc::TimeMillis() }, 0);
+    }).get());
+}
+
+} // namespace WebKit
+
+#endif // USE(LIBWEBRTC) && PLATFORM(COCOA)

Modified: trunk/Source/WebKit/SourcesCocoa.txt (279460 => 279461)


--- trunk/Source/WebKit/SourcesCocoa.txt	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/SourcesCocoa.txt	2021-07-01 10:37:39 UTC (rev 279461)
@@ -54,7 +54,8 @@
 NetworkProcess/webrtc/NetworkRTCProvider.cpp
 NetworkProcess/webrtc/NetworkRTCResolver.cpp
 NetworkProcess/webrtc/NetworkRTCResolverCocoa.cpp
-NetworkProcess/webrtc/NetworkRTCSocketCocoa.mm
+NetworkProcess/webrtc/NetworkRTCTCPSocketCocoa.mm
+NetworkProcess/webrtc/NetworkRTCUDPSocketCocoa.mm
 
 GPUProcess/EntryPoint/Cocoa/XPCService/GPUServiceEntryPoint.mm
 GPUProcess/graphics/RemoteGraphicsContextGLCocoa.cpp

Modified: trunk/Source/WebKit/WebKit.xcodeproj/project.pbxproj (279460 => 279461)


--- trunk/Source/WebKit/WebKit.xcodeproj/project.pbxproj	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/WebKit.xcodeproj/project.pbxproj	2021-07-01 10:37:39 UTC (rev 279461)
@@ -3707,8 +3707,8 @@
 		4103FBA22061BDB800C2EAF8 /* NetworkLoadChecker.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = NetworkLoadChecker.cpp; sourceTree = "<group>"; };
 		410482CB1DDD2FB500F006D0 /* RTCNetwork.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RTCNetwork.cpp; sourceTree = "<group>"; };
 		410482CC1DDD2FB500F006D0 /* RTCNetwork.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RTCNetwork.h; sourceTree = "<group>"; };
-		410BA139257135F2002E2F8A /* NetworkRTCSocketCocoa.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = NetworkRTCSocketCocoa.mm; sourceTree = "<group>"; };
-		410BA13A257135F2002E2F8A /* NetworkRTCSocketCocoa.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NetworkRTCSocketCocoa.h; sourceTree = "<group>"; };
+		410BA139257135F2002E2F8A /* NetworkRTCTCPSocketCocoa.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = NetworkRTCTCPSocketCocoa.mm; sourceTree = "<group>"; };
+		410BA13A257135F2002E2F8A /* NetworkRTCTCPSocketCocoa.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NetworkRTCTCPSocketCocoa.h; sourceTree = "<group>"; };
 		4111436320F677B10026F912 /* InjectUserScriptImmediately.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InjectUserScriptImmediately.h; sourceTree = "<group>"; };
 		411223B72602152B00B0A0B6 /* RTCDataChannelRemoteManager.messages.in */ = {isa = PBXFileReference; lastKnownFileType = text; name = RTCDataChannelRemoteManager.messages.in; path = Network/webrtc/RTCDataChannelRemoteManager.messages.in; sourceTree = "<group>"; };
 		411223BB26024E8000B0A0B6 /* RTCDataChannelRemoteManagerProxy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RTCDataChannelRemoteManagerProxy.h; sourceTree = "<group>"; };
@@ -3841,6 +3841,8 @@
 		41DC45991E3DBB2400B11F51 /* LibWebRTCSocketClient.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LibWebRTCSocketClient.cpp; sourceTree = "<group>"; };
 		41DC459A1E3DBB2400B11F51 /* LibWebRTCSocketClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LibWebRTCSocketClient.h; sourceTree = "<group>"; };
 		41DC45A01E3DC53C00B11F51 /* WebRTCResolver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = WebRTCResolver.cpp; path = Network/webrtc/WebRTCResolver.cpp; sourceTree = "<group>"; };
+		41DD72A6267B8C3000A90C71 /* NetworkRTCUDPSocketCocoa.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = NetworkRTCUDPSocketCocoa.mm; sourceTree = "<group>"; };
+		41DD72A7267B8C3100A90C71 /* NetworkRTCUDPSocketCocoa.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NetworkRTCUDPSocketCocoa.h; sourceTree = "<group>"; };
 		41E0A7C623B6397800561060 /* LibWebRTCCodecsProxy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LibWebRTCCodecsProxy.h; sourceTree = "<group>"; };
 		41E0A7C723B6397900561060 /* LibWebRTCCodecsProxy.messages.in */ = {isa = PBXFileReference; lastKnownFileType = text; path = LibWebRTCCodecsProxy.messages.in; sourceTree = "<group>"; };
 		41E0A7C823B6397900561060 /* LibWebRTCCodecsProxy.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = LibWebRTCCodecsProxy.mm; sourceTree = "<group>"; };
@@ -8416,8 +8418,10 @@
 				4112B5481F9FD3AC00E67875 /* NetworkRTCResolver.h */,
 				4112B5471F9FD3AB00E67986 /* NetworkRTCResolverCocoa.cpp */,
 				4112B5481F9FD3AC00E67986 /* NetworkRTCResolverCocoa.h */,
-				410BA13A257135F2002E2F8A /* NetworkRTCSocketCocoa.h */,
-				410BA139257135F2002E2F8A /* NetworkRTCSocketCocoa.mm */,
+				410BA13A257135F2002E2F8A /* NetworkRTCTCPSocketCocoa.h */,
+				410BA139257135F2002E2F8A /* NetworkRTCTCPSocketCocoa.mm */,
+				41DD72A7267B8C3100A90C71 /* NetworkRTCUDPSocketCocoa.h */,
+				41DD72A6267B8C3000A90C71 /* NetworkRTCUDPSocketCocoa.mm */,
 				411223BC26024E8100B0A0B6 /* RTCDataChannelRemoteManagerProxy.cpp */,
 				411223BB26024E8000B0A0B6 /* RTCDataChannelRemoteManagerProxy.h */,
 				411223BD26024E8100B0A0B6 /* RTCDataChannelRemoteManagerProxy.messages.in */,

Modified: trunk/Source/WebKit/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp (279460 => 279461)


--- trunk/Source/WebKit/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp	2021-07-01 10:35:07 UTC (rev 279460)
+++ trunk/Source/WebKit/WebProcess/Network/webrtc/LibWebRTCSocketFactory.cpp	2021-07-01 10:37:39 UTC (rev 279461)
@@ -54,7 +54,8 @@
     if (!m_connection)
         return;
 
-    m_connection->send(Messages::NetworkRTCProvider::SetPlatformSocketsEnabled(RuntimeEnabledFeatures::sharedFeatures().webRTCPlatformSocketsEnabled()), 0);
+    m_connection->send(Messages::NetworkRTCProvider::SetPlatformTCPSocketsEnabled(RuntimeEnabledFeatures::sharedFeatures().webRTCPlatformTCPSocketsEnabled()), 0);
+    m_connection->send(Messages::NetworkRTCProvider::SetPlatformUDPSocketsEnabled(RuntimeEnabledFeatures::sharedFeatures().webRTCPlatformUDPSocketsEnabled()), 0);
 
     while (!m_pendingMessageTasks.isEmpty())
         m_pendingMessageTasks.takeFirst()(*m_connection);
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to