1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
|
/*
* Copyright (C) 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.
*/
#include "config.h"
#include "NetworkRTCProvider.h"
#if USE(LIBWEBRTC)
#include "DataReference.h"
#include "LibWebRTCNetworkMessages.h"
#include "LibWebRTCSocketClient.h"
#include "Logging.h"
#include "NetworkConnectionToWebProcess.h"
#include "NetworkProcess.h"
#include "NetworkRTCProviderMessages.h"
#include "NetworkSession.h"
#include "RTCPacketOptions.h"
#include "WebRTCResolverMessages.h"
#include <WebCore/LibWebRTCMacros.h>
#include <wtf/MainThread.h>
#include <wtf/text/WTFString.h>
ALLOW_COMMA_BEGIN
#include <webrtc/rtc_base/async_packet_socket.h>
#include <webrtc/rtc_base/logging.h>
ALLOW_COMMA_END
#if PLATFORM(COCOA)
#include "NetworkRTCTCPSocketCocoa.h"
#include "NetworkRTCUDPSocketCocoa.h"
#include "NetworkSessionCocoa.h"
#endif
namespace WebKit {
using namespace WebCore;
#define RTC_RELEASE_LOG(fmt, ...) RELEASE_LOG(Network, "%p - NetworkRTCProvider::" fmt, this, ##__VA_ARGS__)
#define RTC_RELEASE_LOG_ERROR(fmt, ...) RELEASE_LOG_ERROR(Network, "%p - NetworkRTCProvider::" fmt, this, ##__VA_ARGS__)
rtc::Thread& NetworkRTCProvider::rtcNetworkThread()
{
static NeverDestroyed<std::unique_ptr<rtc::Thread>> networkThread;
static std::once_flag onceKey;
std::call_once(onceKey, [] {
networkThread.get() = rtc::Thread::CreateWithSocketServer();
networkThread.get()->SetName("RTC Network Thread", nullptr);
auto result = networkThread.get()->Start();
ASSERT_UNUSED(result, result);
});
return *networkThread.get();
}
#if !RELEASE_LOG_DISABLED
static void doReleaseLogging(rtc::LoggingSeverity severity, const char* message)
{
if (severity == rtc::LS_ERROR)
RELEASE_LOG_ERROR(WebRTC, "LibWebRTC error: %" PUBLIC_LOG_STRING, message);
else
RELEASE_LOG(WebRTC, "LibWebRTC message: %" PUBLIC_LOG_STRING, message);
}
#endif
NetworkRTCProvider::NetworkRTCProvider(NetworkConnectionToWebProcess& connection)
: m_connection(&connection)
, m_ipcConnection(connection.connection())
, m_rtcMonitor(*this)
, m_rtcNetworkThread(rtcNetworkThread())
, m_packetSocketFactory(makeUniqueRefWithoutFastMallocCheck<rtc::BasicPacketSocketFactory>(m_rtcNetworkThread.socketserver()))
#if PLATFORM(COCOA)
, m_sourceApplicationAuditToken(connection.networkProcess().sourceApplicationAuditToken())
#endif
{
#if PLATFORM(COCOA)
if (auto* session = static_cast<NetworkSessionCocoa*>(connection.networkSession()))
m_applicationBundleIdentifier = session->sourceApplicationBundleIdentifier().utf8();
#endif
#if !RELEASE_LOG_DISABLED
rtc::LogMessage::SetLogOutput(WebKit2LogWebRTC.state == WTFLogChannelState::On ? rtc::LS_INFO : rtc::LS_WARNING, doReleaseLogging);
#endif
}
void NetworkRTCProvider::startListeningForIPC()
{
m_connection->connection().addMessageReceiver(*this, *this, Messages::NetworkRTCProvider::messageReceiverName());
}
NetworkRTCProvider::~NetworkRTCProvider()
{
ASSERT(!m_connection);
ASSERT(!m_sockets.size());
ASSERT(!m_rtcMonitor.isStarted());
}
void NetworkRTCProvider::close()
{
RTC_RELEASE_LOG("close");
m_connection->connection().removeMessageReceiver(Messages::NetworkRTCProvider::messageReceiverName());
m_connection = nullptr;
m_rtcMonitor.stopUpdating();
callOnRTCNetworkThread([this, protectedThis = Ref { *this }] {
auto sockets = std::exchange(m_sockets, { });
for (auto& socket : sockets)
socket.second->close();
ASSERT(m_sockets.empty());
#if PLATFORM(COCOA)
m_attributedBundleIdentifiers.clear();
#endif
});
}
void NetworkRTCProvider::createSocket(LibWebRTCSocketIdentifier identifier, std::unique_ptr<rtc::AsyncPacketSocket>&& socket, Socket::Type type, Ref<IPC::Connection>&& connection)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
if (!socket) {
RTC_RELEASE_LOG_ERROR("createSocket with %lu sockets is unable to create a new socket", m_sockets.size());
connection->send(Messages::LibWebRTCNetwork::SignalClose(identifier, 1), 0);
return;
}
addSocket(identifier, makeUnique<LibWebRTCSocketClient>(identifier, *this, WTFMove(socket), type, WTFMove(connection)));
}
#if PLATFORM(COCOA)
const String& NetworkRTCProvider::attributedBundleIdentifierFromPageIdentifier(WebPageProxyIdentifier pageIdentifier)
{
return m_attributedBundleIdentifiers.ensure(pageIdentifier, [&]() -> String {
String value;
callOnMainRunLoopAndWait([&] {
auto* session = m_connection ? m_connection->networkSession() : nullptr;
if (session)
value = session->attributedBundleIdentifierFromPageIdentifier(pageIdentifier).isolatedCopy();
});
return value;
}).iterator->value;
}
#endif
void NetworkRTCProvider::createUDPSocket(LibWebRTCSocketIdentifier identifier, const RTCNetwork::SocketAddress& address, uint16_t minPort, uint16_t maxPort, WebPageProxyIdentifier pageIdentifier, bool isFirstParty, bool isRelayDisabled, WebCore::RegistrableDomain&& domain)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
#if PLATFORM(COCOA)
if (m_platformUDPSocketsEnabled) {
auto socket = makeUnique<NetworkRTCUDPSocketCocoa>(identifier, *this, address.value, m_ipcConnection.copyRef(), String(attributedBundleIdentifierFromPageIdentifier(pageIdentifier)), isFirstParty, isRelayDisabled, WTFMove(domain));
addSocket(identifier, WTFMove(socket));
return;
}
#endif
std::unique_ptr<rtc::AsyncPacketSocket> socket(m_packetSocketFactory->CreateUdpSocket(address.value, minPort, maxPort));
createSocket(identifier, WTFMove(socket), Socket::Type::UDP, m_ipcConnection.copyRef());
}
#if !PLATFORM(COCOA)
rtc::ProxyInfo NetworkRTCProvider::proxyInfoFromSession(const RTCNetwork::SocketAddress&, NetworkSession&)
{
return { };
}
#endif
void NetworkRTCProvider::createClientTCPSocket(LibWebRTCSocketIdentifier identifier, const RTCNetwork::SocketAddress& localAddress, const RTCNetwork::SocketAddress& remoteAddress, String&& userAgent, int options, WebPageProxyIdentifier pageIdentifier, bool isFirstParty, bool isRelayDisabled, WebCore::RegistrableDomain&& domain)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
#if PLATFORM(COCOA)
if (m_platformTCPSocketsEnabled) {
auto socket = NetworkRTCTCPSocketCocoa::createClientTCPSocket(identifier, *this, remoteAddress.value, options, attributedBundleIdentifierFromPageIdentifier(pageIdentifier), isFirstParty, isRelayDisabled, domain, m_ipcConnection.copyRef());
if (socket)
addSocket(identifier, WTFMove(socket));
else
signalSocketIsClosed(identifier);
return;
}
#endif
callOnMainRunLoop([this, protectedThis = Ref { *this }, identifier, localAddress, remoteAddress, userAgent = WTFMove(userAgent).isolatedCopy(), options]() mutable {
if (!m_connection)
return;
auto* session = m_connection->networkSession();
if (!session) {
signalSocketIsClosed(identifier);
return;
}
callOnRTCNetworkThread([this, protectedThis = Ref { *this }, identifier, localAddress = RTCNetwork::isolatedCopy(localAddress.value), remoteAddress = RTCNetwork::isolatedCopy(remoteAddress.value), proxyInfo = proxyInfoFromSession(remoteAddress, *session), userAgent = WTFMove(userAgent).isolatedCopy(), options]() mutable {
rtc::PacketSocketTcpOptions tcpOptions;
tcpOptions.opts = options;
std::unique_ptr<rtc::AsyncPacketSocket> socket(m_packetSocketFactory->CreateClientTcpSocket(localAddress, remoteAddress, proxyInfo, userAgent.utf8().data(), tcpOptions));
createSocket(identifier, WTFMove(socket), Socket::Type::ClientTCP, m_ipcConnection.copyRef());
});
});
}
void NetworkRTCProvider::wrapNewTCPConnection(LibWebRTCSocketIdentifier identifier, LibWebRTCSocketIdentifier newConnectionSocketIdentifier)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
auto socket = m_pendingIncomingSockets.take(newConnectionSocketIdentifier);
RELEASE_LOG_IF(!socket, WebRTC, "NetworkRTCProvider::wrapNewTCPConnection received an invalid socket identifier");
if (socket)
addSocket(identifier, makeUnique<LibWebRTCSocketClient>(identifier, *this, WTFMove(socket), Socket::Type::ServerConnectionTCP, m_ipcConnection.copyRef()));
}
void NetworkRTCProvider::sendToSocket(LibWebRTCSocketIdentifier identifier, const IPC::DataReference& data, RTCNetwork::SocketAddress&& address, RTCPacketOptions&& options)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
auto iterator = m_sockets.find(identifier);
if (iterator == m_sockets.end())
return;
iterator->second->sendTo(data.data(), data.size(), address.value, options.options);
}
void NetworkRTCProvider::closeSocket(LibWebRTCSocketIdentifier identifier)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
auto iterator = m_sockets.find(identifier);
if (iterator == m_sockets.end())
return;
iterator->second->close();
}
void NetworkRTCProvider::doSocketTaskOnRTCNetworkThread(LibWebRTCSocketIdentifier identifier, Function<void(Socket&)>&& callback)
{
callOnRTCNetworkThread([this, protectedThis = Ref { *this }, identifier, callback = WTFMove(callback)]() mutable {
auto iterator = m_sockets.find(identifier);
if (iterator == m_sockets.end())
return;
callback(*iterator->second);
});
}
void NetworkRTCProvider::setSocketOption(LibWebRTCSocketIdentifier identifier, int option, int value)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
auto iterator = m_sockets.find(identifier);
if (iterator == m_sockets.end())
return;
iterator->second->setOption(option, value);
}
void NetworkRTCProvider::addSocket(LibWebRTCSocketIdentifier identifier, std::unique_ptr<Socket>&& socket)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
ASSERT(socket);
m_sockets.emplace(identifier, WTFMove(socket));
RTC_RELEASE_LOG("new socket %" PRIu64 ", total socket number is %lu", identifier.toUInt64(), m_sockets.size());
if (m_sockets.size() > maxSockets) {
auto socketIdentifierToClose = m_sockets.begin()->first;
RTC_RELEASE_LOG_ERROR("too many sockets, closing %" PRIu64, socketIdentifierToClose.toUInt64());
closeSocket(socketIdentifierToClose);
ASSERT(m_sockets.find(socketIdentifierToClose) == m_sockets.end());
}
}
std::unique_ptr<NetworkRTCProvider::Socket> NetworkRTCProvider::takeSocket(LibWebRTCSocketIdentifier identifier)
{
ASSERT(m_rtcNetworkThread.IsCurrent());
auto iterator = m_sockets.find(identifier);
if (iterator == m_sockets.end())
return nullptr;
auto socket = WTFMove(iterator->second);
m_sockets.erase(iterator);
return socket;
}
void NetworkRTCProvider::dispatch(Function<void()>&& callback)
{
callOnRTCNetworkThread((WTFMove(callback)));
}
void NetworkRTCProvider::createResolver(LibWebRTCResolverIdentifier identifier, String&& address)
{
if (!isMainRunLoop()) {
callOnMainRunLoop([this, protectedThis = Ref { *this }, identifier, address = WTFMove(address).isolatedCopy()]() mutable {
if (!m_connection)
return;
createResolver(identifier, WTFMove(address));
});
return;
}
WebCore::DNSCompletionHandler completionHandler = [connection = m_connection, identifier](auto&& result) {
ASSERT(isMainRunLoop());
if (!connection)
return;
if (!result.has_value()) {
if (result.error() != WebCore::DNSError::Cancelled)
connection->connection().send(Messages::WebRTCResolver::ResolvedAddressError(1), identifier);
return;
}
Vector<RTCNetwork::IPAddress> ipAddresses;
ipAddresses.reserveInitialCapacity(result.value().size());
for (auto& address : result.value()) {
if (address.isIPv4())
ipAddresses.uncheckedAppend(rtc::IPAddress { address.ipv4Address() });
else if (address.isIPv6())
ipAddresses.uncheckedAppend(rtc::IPAddress { address.ipv6Address() });
}
connection->connection().send(Messages::WebRTCResolver::SetResolvedAddress(ipAddresses), identifier);
};
WebCore::resolveDNS(address, identifier.toUInt64(), WTFMove(completionHandler));
}
void NetworkRTCProvider::stopResolver(LibWebRTCResolverIdentifier identifier)
{
if (!isMainRunLoop()) {
callOnMainRunLoop([this, protectedThis = Ref { *this }, identifier] {
if (!m_connection)
return;
stopResolver(identifier);
});
return;
}
WebCore::stopResolveDNS(identifier.toUInt64());
}
void NetworkRTCProvider::callOnRTCNetworkThread(Function<void()>&& callback)
{
m_rtcNetworkThread.PostTask(WTFMove(callback));
}
void NetworkRTCProvider::signalSocketIsClosed(LibWebRTCSocketIdentifier identifier)
{
m_connection->connection().send(Messages::LibWebRTCNetwork::SignalClose(identifier, 1), 0);
}
#undef RTC_RELEASE_LOG
#undef RTC_RELEASE_LOG_ERROR
} // namespace WebKit
#endif // USE(LIBWEBRTC)
|