Files
palemoon27/dom/network/TCPSocketParent.cpp
T
roytam1 17528bae8d import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1243352 - attribute a value for ProxyHandlerInfo::mPrefAction in ProxyHandlerInfo::SetPreferredAction. r=blassey (577c23e4cb)
- Bug 1266433 - Send Push observer notifications to parent and content processes. f=janx r=dragana (768c173c2c)
- Bug 1267493 - Replace isURIPotentiallyTrustworthy usage in Push with a testing pref. r=dragana (96434b90d9)
- Bug 1266433 - Send an observer notification when a push subscription is lost. f=janx r=dragana (a7c7277e02)
- Bug 1247685 - Send subscription keys to the Push server. r=mt (651fc0cad3)
- Bug 1266540 - Stub out Push error reporting for the GCM and H2 backends. r=wchen (fd00c311aa)
- Bug 1266623 - Up/down mix WASAPI capture streams when stream formats don't match. r=padenot (ca92ec20ab)
- Bug 1267930 - When the wasapi rendering loop is stuck and we're shuttin down, leak the thread and continue the shutdown process. r=kinetik (04419ad94d)
- Bug 1269692 - Update cubeb to revision 17e3048d0afa1152776fb1867cdb61c49fae69e4. (3de098f4bb)
- Bug 1251502 - Update cubeb's udpate.sh script to account for new files. r=kinetik (a3ae5f27c1)
- Bug 1243234 - Hide MP4Metadata behind an impl pointer. r=giles (1543bedf28)
- Bug 1243234 - Update rust mp4parse telemetry reporting. r=kinetik (bb5c999c06)
- Bug 1242807 - Fix mp4parse-rust's error reporting via telemetry. r=giles (a3ca1b133b)
- Bug 1243234 - Move mp4parse-rust code into MP4MetadataRust impl. r=giles (ec4d6bcf0e)
- Bug 1243234 - Remove now-unnecessary StagefrightPrivate wrapper. r=giles (1e2c54232b)
- Bug 1243234 - Move mp4parse-rust initialization into constructor and clean up try_rust. r=giles (291c01f45a)
- Bug 1243234 - Update rust mp4parse to v0.2.1. r=kinetik (d2774346cd)
- Bug 1264622: [MP4] Resync stagefright's updateAudioTrackInfoFromESDS_MPEG4Audio with upstream. r=kentuckyfriedtakahe (b4b596507b)
- Bug 1254721: Ensure consistency between Cenc offsets and sizes table. r=gerald (59bd7122d1)
- Bug 1151202 - libstagefright: Fix compilation for systems without <sys/cdefs.h>. r=cpearce (e219658c31)
- Bug 1255866 - stagefright: Fix unused variable warnings. r=ajones (62afc26384)
- Bug 1251821: increase UDP socket send buffer on Win 7 r=jdm,jesup (e0d6e545f4)
- Bug 929977: Add support for RFC 7675 ICE consent freshness. r=bwc,mt (ea8a565a65)
- Bug 1231981 - Part 1: Very basic test TURN server for running in CI. r=ahal,drno (c98a79810b)
- Bug 1231981 - Part 2: A websocket-to-process bridge script that can be used by JS to launch an ICE server for testing. r=ahal (5bdb00dfd1)
- Bug 1231981 - Part 2.1: Only run the websocket/process bridge for media tests. r=ahal (86f97e2eb6)
- Bug 1225729: Whitelist specific bad RTCP timestamp value r=drno (f0c8402fd0)
- Bug 1193045 - Check selected attribute for all calls. r=bwc (7eb4095c34)
- Bug 1213056 - update tests to use maplike getStats. r=bwc (d27f997290)
- Bug 1231981 - Part 3: Set up TURN server for webrtc mochitests, when configured to. r=drno (38e4455eec)
- Bug 1231975 - Part 1: Basic audio mochitests for NAT scenarios. r=drno (16efaf581e)
- Bug 1231975 - Part 2: Break a reference cycle between NrTcpSocketIpc and TCPSocketChild, in the same manner as the UDP case. r=mcmanus (1fa55e3e5f)
2024-08-29 00:15:44 +08:00

453 lines
12 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "TCPSocketParent.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "nsJSUtils.h"
#include "mozilla/unused.h"
#include "mozilla/AppProcessChecker.h"
#include "mozilla/net/NeckoCommon.h"
#include "mozilla/net/PNeckoParent.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/TabParent.h"
#include "mozilla/HoldDropJSObjects.h"
#include "nsISocketTransportService.h"
#include "nsISocketTransport.h"
#include "nsIScriptSecurityManager.h"
#include "nsNetUtil.h"
//
// set NSPR_LOG_MODULES=TCPSocket:5
//
extern mozilla::LazyLogModule gTCPSocketLog;
#define TCPSOCKET_LOG(args) MOZ_LOG(gTCPSocketLog, mozilla::LogLevel::Debug, args)
#define TCPSOCKET_LOG_ENABLED() MOZ_LOG_TEST(gTCPSocketLog, mozilla::LogLevel::Debug)
namespace IPC {
//Defined in TCPSocketChild.cpp
extern bool
DeserializeArrayBuffer(JSContext* aCx,
const InfallibleTArray<uint8_t>& aBuffer,
JS::MutableHandle<JS::Value> aVal);
} // namespace IPC
namespace mozilla {
namespace dom {
static void
FireInteralError(mozilla::net::PTCPSocketParent* aActor, uint32_t aLineNo)
{
mozilla::Unused <<
aActor->SendCallback(NS_LITERAL_STRING("onerror"),
TCPError(NS_LITERAL_STRING("InvalidStateError"), NS_LITERAL_STRING("Internal error")),
static_cast<uint32_t>(TCPReadyState::Connecting));
}
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TCPSocketParentBase)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION(TCPSocketParentBase, mSocket)
NS_IMPL_CYCLE_COLLECTING_ADDREF(TCPSocketParentBase)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TCPSocketParentBase)
TCPSocketParentBase::TCPSocketParentBase()
: mIPCOpen(false)
{
mObserver = new mozilla::net::OfflineObserver(this);
}
TCPSocketParentBase::~TCPSocketParentBase()
{
if (mObserver) {
mObserver->RemoveObserver();
}
}
uint32_t
TCPSocketParent::GetAppId()
{
const PContentParent *content = Manager()->Manager();
if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
TabParent *tab = TabParent::GetFrom(browser);
return tab->OwnAppId();
} else {
return nsIScriptSecurityManager::UNKNOWN_APP_ID;
}
};
bool
TCPSocketParent::GetInBrowser()
{
const PContentParent *content = Manager()->Manager();
if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
TabParent *tab = TabParent::GetFrom(browser);
return tab->IsBrowserElement();
} else {
return false;
}
}
nsresult
TCPSocketParent::OfflineNotification(nsISupports *aSubject)
{
nsCOMPtr<nsIAppOfflineInfo> info(do_QueryInterface(aSubject));
if (!info) {
return NS_OK;
}
uint32_t targetAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
info->GetAppId(&targetAppId);
// Obtain App ID
uint32_t appId = GetAppId();
if (appId != targetAppId) {
return NS_OK;
}
// If the app is offline, close the socket
if (mSocket && NS_IsAppOffline(appId)) {
mSocket->Close();
mSocket = nullptr;
}
return NS_OK;
}
void
TCPSocketParentBase::ReleaseIPDLReference()
{
MOZ_ASSERT(mIPCOpen);
mIPCOpen = false;
this->Release();
}
void
TCPSocketParentBase::AddIPDLReference()
{
MOZ_ASSERT(!mIPCOpen);
mIPCOpen = true;
this->AddRef();
}
NS_IMETHODIMP_(MozExternalRefCountType) TCPSocketParent::Release(void)
{
nsrefcnt refcnt = TCPSocketParentBase::Release();
if (refcnt == 1 && mIPCOpen) {
mozilla::Unused << PTCPSocketParent::SendRequestDelete();
return 1;
}
return refcnt;
}
bool
TCPSocketParent::RecvOpen(const nsString& aHost, const uint16_t& aPort, const bool& aUseSSL,
const bool& aUseArrayBuffers)
{
// We don't have browser actors in xpcshell, and hence can't run automated
// tests without this loophole.
if (net::UsingNeckoIPCSecurity() &&
!AssertAppProcessPermission(Manager()->Manager(), "tcp-socket")) {
FireInteralError(this, __LINE__);
return true;
}
// Obtain App ID
uint32_t appId = GetAppId();
bool inBrowser = GetInBrowser();
if (NS_IsAppOffline(appId)) {
NS_ERROR("Can't open socket because app is offline");
FireInteralError(this, __LINE__);
return true;
}
mSocket = new TCPSocket(nullptr, aHost, aPort, aUseSSL, aUseArrayBuffers);
mSocket->SetAppIdAndBrowser(appId, inBrowser);
mSocket->SetSocketBridgeParent(this);
NS_ENSURE_SUCCESS(mSocket->Init(), true);
return true;
}
bool
TCPSocketParent::RecvOpenBind(const nsCString& aRemoteHost,
const uint16_t& aRemotePort,
const nsCString& aLocalAddr,
const uint16_t& aLocalPort,
const bool& aUseSSL,
const bool& aUseArrayBuffers,
const nsCString& aFilter)
{
if (net::UsingNeckoIPCSecurity() &&
!AssertAppProcessPermission(Manager()->Manager(), "tcp-socket")) {
FireInteralError(this, __LINE__);
return true;
}
nsresult rv;
nsCOMPtr<nsISocketTransportService> sts =
do_GetService("@mozilla.org/network/socket-transport-service;1", &rv);
if (NS_FAILED(rv)) {
FireInteralError(this, __LINE__);
return true;
}
nsCOMPtr<nsISocketTransport> socketTransport;
rv = sts->CreateTransport(nullptr, 0,
aRemoteHost, aRemotePort,
nullptr, getter_AddRefs(socketTransport));
if (NS_FAILED(rv)) {
FireInteralError(this, __LINE__);
return true;
}
PRNetAddr prAddr;
if (PR_SUCCESS != PR_InitializeNetAddr(PR_IpAddrAny, aLocalPort, &prAddr)) {
FireInteralError(this, __LINE__);
return true;
}
if (PR_SUCCESS != PR_StringToNetAddr(aLocalAddr.BeginReading(), &prAddr)) {
FireInteralError(this, __LINE__);
return true;
}
mozilla::net::NetAddr addr;
PRNetAddrToNetAddr(&prAddr, &addr);
rv = socketTransport->Bind(&addr);
if (NS_FAILED(rv)) {
FireInteralError(this, __LINE__);
return true;
}
if (!aFilter.IsEmpty()) {
nsAutoCString contractId(NS_NETWORK_TCP_SOCKET_FILTER_HANDLER_PREFIX);
contractId.Append(aFilter);
nsCOMPtr<nsISocketFilterHandler> filterHandler =
do_GetService(contractId.get());
if (!filterHandler) {
NS_ERROR("Content doesn't have a valid filter");
FireInteralError(this, __LINE__);
return true;
}
rv = filterHandler->NewFilter(getter_AddRefs(mFilter));
if (NS_FAILED(rv)) {
NS_ERROR("Cannot create filter that content specified");
FireInteralError(this, __LINE__);
return true;
}
}
// Obtain App ID
uint32_t appId = nsIScriptSecurityManager::NO_APP_ID;
bool inBrowser = false;
const PContentParent *content = Manager()->Manager();
if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
// appId's are for B2G only currently, where managees.Count() == 1
// This is not guaranteed currently in Desktop, so skip this there.
TabParent *tab = TabParent::GetFrom(browser);
appId = tab->OwnAppId();
inBrowser = tab->IsBrowserElement();
}
mSocket = new TCPSocket(nullptr, NS_ConvertUTF8toUTF16(aRemoteHost), aRemotePort, aUseSSL, aUseArrayBuffers);
mSocket->SetAppIdAndBrowser(appId, inBrowser);
mSocket->SetSocketBridgeParent(this);
rv = mSocket->InitWithUnconnectedTransport(socketTransport);
NS_ENSURE_SUCCESS(rv, true);
return true;
}
bool
TCPSocketParent::RecvStartTLS()
{
NS_ENSURE_TRUE(mSocket, true);
ErrorResult rv;
mSocket->UpgradeToSecure(rv);
NS_ENSURE_FALSE(rv.Failed(), true);
return true;
}
bool
TCPSocketParent::RecvSuspend()
{
NS_ENSURE_TRUE(mSocket, true);
mSocket->Suspend();
return true;
}
bool
TCPSocketParent::RecvResume()
{
NS_ENSURE_TRUE(mSocket, true);
ErrorResult rv;
mSocket->Resume(rv);
NS_ENSURE_FALSE(rv.Failed(), true);
return true;
}
bool
TCPSocketParent::RecvData(const SendableData& aData,
const uint32_t& aTrackingNumber)
{
ErrorResult rv;
if (mFilter) {
mozilla::net::NetAddr addr; // dummy value
bool allowed;
MOZ_ASSERT(aData.type() == SendableData::TArrayOfuint8_t,
"Unsupported data type for filtering");
const InfallibleTArray<uint8_t>& data(aData.get_ArrayOfuint8_t());
nsresult nsrv = mFilter->FilterPacket(&addr, data.Elements(),
data.Length(),
nsISocketFilter::SF_OUTGOING,
&allowed);
// Reject sending of unallowed data
if (NS_WARN_IF(NS_FAILED(nsrv)) || !allowed) {
TCPSOCKET_LOG(("%s: Dropping outgoing TCP packet", __FUNCTION__));
return false;
}
}
switch (aData.type()) {
case SendableData::TArrayOfuint8_t: {
AutoSafeJSContext autoCx;
JS::Rooted<JS::Value> val(autoCx);
const nsTArray<uint8_t>& buffer = aData.get_ArrayOfuint8_t();
bool ok = IPC::DeserializeArrayBuffer(autoCx, buffer, &val);
NS_ENSURE_TRUE(ok, true);
RootedTypedArray<ArrayBuffer> data(autoCx);
data.Init(&val.toObject());
Optional<uint32_t> byteLength(buffer.Length());
mSocket->SendWithTrackingNumber(autoCx, data, 0, byteLength, aTrackingNumber, rv);
break;
}
case SendableData::TnsCString: {
const nsCString& strData = aData.get_nsCString();
mSocket->SendWithTrackingNumber(strData, aTrackingNumber, rv);
break;
}
default:
MOZ_CRASH("unexpected SendableData type");
}
NS_ENSURE_SUCCESS(rv.StealNSResult(), true);
return true;
}
bool
TCPSocketParent::RecvClose()
{
NS_ENSURE_TRUE(mSocket, true);
mSocket->Close();
return true;
}
void
TCPSocketParent::FireErrorEvent(const nsAString& aName, const nsAString& aType, TCPReadyState aReadyState)
{
SendEvent(NS_LITERAL_STRING("error"), TCPError(nsString(aName), nsString(aType)), aReadyState);
}
void
TCPSocketParent::FireEvent(const nsAString& aType, TCPReadyState aReadyState)
{
return SendEvent(aType, mozilla::void_t(), aReadyState);
}
void
TCPSocketParent::FireArrayBufferDataEvent(nsTArray<uint8_t>& aBuffer, TCPReadyState aReadyState)
{
InfallibleTArray<uint8_t> arr;
arr.SwapElements(aBuffer);
if (mFilter) {
bool allowed;
mozilla::net::NetAddr addr;
nsresult nsrv = mFilter->FilterPacket(&addr, arr.Elements(), arr.Length(),
nsISocketFilter::SF_INCOMING,
&allowed);
// receiving unallowed data, drop it.
if (NS_WARN_IF(NS_FAILED(nsrv)) || !allowed) {
TCPSOCKET_LOG(("%s: Dropping incoming TCP packet", __FUNCTION__));
return;
}
}
SendableData data(arr);
SendEvent(NS_LITERAL_STRING("data"), data, aReadyState);
}
void
TCPSocketParent::FireStringDataEvent(const nsACString& aData, TCPReadyState aReadyState)
{
SendableData data((nsCString(aData)));
MOZ_ASSERT(!mFilter, "Socket filtering doesn't support nsCString");
SendEvent(NS_LITERAL_STRING("data"), data, aReadyState);
}
void
TCPSocketParent::SendEvent(const nsAString& aType, CallbackData aData, TCPReadyState aReadyState)
{
mozilla::Unused << PTCPSocketParent::SendCallback(nsString(aType), aData,
static_cast<uint32_t>(aReadyState));
}
void
TCPSocketParent::SetSocket(TCPSocket *socket)
{
mSocket = socket;
}
nsresult
TCPSocketParent::GetHost(nsAString& aHost)
{
if (!mSocket) {
NS_ERROR("No internal socket instance mSocket!");
return NS_ERROR_FAILURE;
}
mSocket->GetHost(aHost);
return NS_OK;
}
nsresult
TCPSocketParent::GetPort(uint16_t* aPort)
{
if (!mSocket) {
NS_ERROR("No internal socket instance mSocket!");
return NS_ERROR_FAILURE;
}
*aPort = mSocket->Port();
return NS_OK;
}
void
TCPSocketParent::ActorDestroy(ActorDestroyReason why)
{
if (mSocket) {
mSocket->Close();
}
mSocket = nullptr;
}
bool
TCPSocketParent::RecvRequestDelete()
{
mozilla::Unused << Send__delete__(this);
return true;
}
} // namespace dom
} // namespace mozilla