Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=4 sw=2 cindent et: */
/* 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 "mozilla/DebugOnly.h"
#include "nsIOService.h"
#include "nsIProtocolHandler.h"
#include "nsIFileProtocolHandler.h"
#include "nscore.h"
#include "nsIURI.h"
#include "prprf.h"
#include "netCore.h"
#include "nsIObserverService.h"
#include "nsXPCOM.h"
#include "nsIProxiedProtocolHandler.h"
#include "nsIProxyInfo.h"
#include "nsDNSService2.h"
#include "nsEscape.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsCRT.h"
#include "nsSimpleNestedURI.h"
#include "nsSocketTransport2.h"
#include "nsTArray.h"
#include "nsIConsoleService.h"
#include "nsIUploadChannel2.h"
#include "nsXULAppAPI.h"
#include "nsIProtocolProxyCallback.h"
#include "nsICancelable.h"
#include "nsINetworkLinkService.h"
#include "nsAsyncRedirectVerifyHelper.h"
#include "nsURLHelper.h"
#include "nsIProtocolProxyService2.h"
#include "MainThreadUtils.h"
#include "nsINode.h"
#include "nsIWebTransport.h"
#include "nsIWidget.h"
#include "nsThreadUtils.h"
#include "WebTransportSessionProxy.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/Components.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/net/NeckoCommon.h"
#include "mozilla/Services.h"
#include "mozilla/Telemetry.h"
#include "mozilla/net/DNS.h"
#include "mozilla/ipc/URIUtils.h"
#include "mozilla/net/NeckoChild.h"
#include "mozilla/net/NeckoParent.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/nsHTTPSOnlyUtils.h"
#include "mozilla/dom/ServiceWorkerDescriptor.h"
#include "mozilla/net/CaptivePortalService.h"
#include "mozilla/net/NetworkConnectivityService.h"
#include "mozilla/net/SocketProcessHost.h"
#include "mozilla/net/SocketProcessParent.h"
#include "mozilla/net/SSLTokensCache.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "mozilla/Unused.h"
#include "nsContentSecurityManager.h"
#include "nsContentUtils.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/glean/GleanMetrics.h"
#include "nsNSSComponent.h"
#include "IPv4Parser.h"
#include "ssl.h"
#include "StaticComponents.h"
#ifdef MOZ_WIDGET_ANDROID
# include <regex>
# include "AndroidBridge.h"
# include "mozilla/java/GeckoAppShellWrappers.h"
# include "mozilla/jni/Utils.h"
#endif
namespace mozilla {
namespace net {
using mozilla::Maybe;
using mozilla::dom::ClientInfo;
using mozilla::dom::ServiceWorkerDescriptor;
#define PORT_PREF_PREFIX "network.security.ports."
#define PORT_PREF(x) PORT_PREF_PREFIX x
#define MANAGE_OFFLINE_STATUS_PREF "network.manage-offline-status"
// Nb: these have been misnomers since bug 715770 removed the buffer cache.
// "network.segment.count" and "network.segment.size" would be better names,
// but the old names are still used to preserve backward compatibility.
#define NECKO_BUFFER_CACHE_COUNT_PREF "network.buffer.cache.count"
#define NECKO_BUFFER_CACHE_SIZE_PREF "network.buffer.cache.size"
#define NETWORK_CAPTIVE_PORTAL_PREF "network.captive-portal-service.enabled"
#define WEBRTC_PREF_PREFIX "media.peerconnection."
#define NETWORK_DNS_PREF "network.dns."
#define FORCE_EXTERNAL_PREF_PREFIX "network.protocol-handler.external."
#define SIMPLE_URI_SCHEMES_PREF "network.url.simple_uri_schemes"
nsIOService* gIOService;
static bool gHasWarnedUploadChannel2;
static bool gCaptivePortalEnabled = false;
static LazyLogModule gIOServiceLog("nsIOService");
#undef LOG
#define LOG(args) MOZ_LOG(gIOServiceLog, LogLevel::Debug, args)
// A general port blacklist. Connections to these ports will not be allowed
// unless the protocol overrides.
//
// This list is to be kept in sync with "bad ports" as defined in the
// WHATWG Fetch standard at <https://fetch.spec.whatwg.org/#port-blocking>
int16_t gBadPortList[] = {
1, // tcpmux
7, // echo
9, // discard
11, // systat
13, // daytime
15, // netstat
17, // qotd
19, // chargen
20, // ftp-data
21, // ftp
22, // ssh
23, // telnet
25, // smtp
37, // time
42, // name
43, // nicname
53, // domain
69, // tftp
77, // priv-rjs
79, // finger
87, // ttylink
95, // supdup
101, // hostriame
102, // iso-tsap
103, // gppitnp
104, // acr-nema
109, // pop2
110, // pop3
111, // sunrpc
113, // auth
115, // sftp
117, // uucp-path
119, // nntp
123, // ntp
135, // loc-srv / epmap
137, // netbios
139, // netbios
143, // imap2
161, // snmp
179, // bgp
389, // ldap
427, // afp (alternate)
465, // smtp (alternate)
512, // print / exec
513, // login
514, // shell
515, // printer
526, // tempo
530, // courier
531, // chat
532, // netnews
540, // uucp
548, // afp
554, // rtsp
556, // remotefs
563, // nntp+ssl
587, // smtp (outgoing)
601, // syslog-conn
636, // ldap+ssl
989, // ftps-data
990, // ftps
993, // imap+ssl
995, // pop3+ssl
1719, // h323gatestat
1720, // h323hostcall
1723, // pptp
2049, // nfs
3659, // apple-sasl
4045, // lockd
4160, // sieve
5060, // sip
5061, // sips
6000, // x11
6566, // sane-port
6665, // irc (alternate)
6666, // irc (alternate)
6667, // irc (default)
6668, // irc (alternate)
6669, // irc (alternate)
6679, // osaut
6697, // irc+tls
10080, // amanda
0, // Sentinel value: This MUST be zero
};
static const char kProfileChangeNetTeardownTopic[] =
"profile-change-net-teardown";
static const char kProfileChangeNetRestoreTopic[] =
"profile-change-net-restore";
static const char kProfileDoChange[] = "profile-do-change";
// Necko buffer defaults
uint32_t nsIOService::gDefaultSegmentSize = 4096;
uint32_t nsIOService::gDefaultSegmentCount = 24;
uint32_t nsIOService::sSocketProcessCrashedCount = 0;
////////////////////////////////////////////////////////////////////////////////
nsIOService::nsIOService()
: mLastOfflineStateChange(PR_IntervalNow()),
mLastConnectivityChange(PR_IntervalNow()),
mLastNetworkLinkChange(PR_IntervalNow()) {}
static const char* gCallbackPrefs[] = {
PORT_PREF_PREFIX,
MANAGE_OFFLINE_STATUS_PREF,
NECKO_BUFFER_CACHE_COUNT_PREF,
NECKO_BUFFER_CACHE_SIZE_PREF,
NETWORK_CAPTIVE_PORTAL_PREF,
FORCE_EXTERNAL_PREF_PREFIX,
SIMPLE_URI_SCHEMES_PREF,
nullptr,
};
static const char* gCallbackPrefsForSocketProcess[] = {
WEBRTC_PREF_PREFIX,
NETWORK_DNS_PREF,
"network.send_ODA_to_content_directly",
"network.trr.",
"doh-rollout.",
"network.dns.disableIPv6",
"network.offline-mirrors-connectivity",
"network.disable-localhost-when-offline",
"network.proxy.parse_pac_on_socket_process",
"network.proxy.allow_hijacking_localhost",
"network.connectivity-service.",
"network.captive-portal-service.testMode",
"network.socket.ip_addr_any.disabled",
nullptr,
};
static const char* gCallbackSecurityPrefs[] = {
// Note the prefs listed below should be in sync with the code in
// HandleTLSPrefChange().
"security.tls.version.min",
"security.tls.version.max",
"security.tls.version.enable-deprecated",
"security.tls.hello_downgrade_check",
"security.ssl.require_safe_negotiation",
"security.ssl.enable_false_start",
"security.ssl.enable_alpn",
"security.tls.enable_0rtt_data",
"security.ssl.disable_session_identifiers",
"security.tls.enable_post_handshake_auth",
"security.tls.enable_delegated_credentials",
nullptr,
};
nsresult nsIOService::Init() {
SSLTokensCache::Init();
InitializeCaptivePortalService();
// setup our bad port list stuff
for (int i = 0; gBadPortList[i]; i++) {
// We can't be accessed by another thread yet
MOZ_PUSH_IGNORE_THREAD_SAFETY
mRestrictedPortList.AppendElement(gBadPortList[i]);
MOZ_POP_THREAD_SAFETY
}
// Further modifications to the port list come from prefs
Preferences::RegisterPrefixCallbacks(nsIOService::PrefsChanged,
gCallbackPrefs, this);
PrefsChanged();
mSocketProcessTopicBlockedList.Insert(
nsLiteralCString(NS_XPCOM_WILL_SHUTDOWN_OBSERVER_ID));
mSocketProcessTopicBlockedList.Insert(
nsLiteralCString(NS_XPCOM_SHUTDOWN_OBSERVER_ID));
mSocketProcessTopicBlockedList.Insert("xpcom-shutdown-threads"_ns);
mSocketProcessTopicBlockedList.Insert("profile-do-change"_ns);
mSocketProcessTopicBlockedList.Insert("network:socket-process-crashed"_ns);
// Register for profile change notifications
mObserverService = services::GetObserverService();
AddObserver(this, kProfileChangeNetTeardownTopic, true);
AddObserver(this, kProfileChangeNetRestoreTopic, true);
AddObserver(this, kProfileDoChange, true);
AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
AddObserver(this, NS_NETWORK_LINK_TOPIC, true);
AddObserver(this, NS_NETWORK_ID_CHANGED_TOPIC, true);
AddObserver(this, NS_WIDGET_WAKE_OBSERVER_TOPIC, true);
// Register observers for sending notifications to nsSocketTransportService
if (XRE_IsParentProcess()) {
AddObserver(this, "profile-initial-state", true);
AddObserver(this, NS_WIDGET_SLEEP_OBSERVER_TOPIC, true);
}
if (IsSocketProcessChild()) {
Preferences::RegisterCallbacks(nsIOService::OnTLSPrefChange,
gCallbackSecurityPrefs, this);
}
gIOService = this;
InitializeNetworkLinkService();
InitializeProtocolProxyService();
SetOffline(false);
return NS_OK;
}
NS_IMETHODIMP
nsIOService::AddObserver(nsIObserver* aObserver, const char* aTopic,
bool aOwnsWeak) {
if (!mObserverService) {
return NS_ERROR_FAILURE;
}
// Register for the origional observer.
nsresult rv = mObserverService->AddObserver(aObserver, aTopic, aOwnsWeak);
if (NS_FAILED(rv)) {
return rv;
}
if (!XRE_IsParentProcess()) {
return NS_OK;
}
nsAutoCString topic(aTopic);
// This happens when AddObserver() is called by nsIOService::Init(). We don't
// want to add nsIOService again.
if (SameCOMIdentity(aObserver, static_cast<nsIObserver*>(this))) {
mIOServiceTopicList.Insert(topic);
return NS_OK;
}
if (!UseSocketProcess()) {
return NS_OK;
}
if (mSocketProcessTopicBlockedList.Contains(topic)) {
return NS_ERROR_FAILURE;
}
// Avoid registering duplicate topics.
if (mObserverTopicForSocketProcess.Contains(topic)) {
return NS_ERROR_FAILURE;
}
mObserverTopicForSocketProcess.Insert(topic);
// Avoid registering duplicate topics.
if (mIOServiceTopicList.Contains(topic)) {
return NS_ERROR_FAILURE;
}
return mObserverService->AddObserver(this, aTopic, true);
}
NS_IMETHODIMP
nsIOService::RemoveObserver(nsIObserver* aObserver, const char* aTopic) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsIOService::EnumerateObservers(const char* aTopic,
nsISimpleEnumerator** anEnumerator) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsIOService::NotifyObservers(nsISupports* aSubject,
const char* aTopic,
const char16_t* aSomeData) {
return NS_ERROR_NOT_IMPLEMENTED;
}
nsIOService::~nsIOService() {
if (gIOService) {
MOZ_ASSERT(gIOService == this);
gIOService = nullptr;
}
}
#ifdef MOZ_WIDGET_ANDROID
bool nsIOService::ShouldAddAdditionalSearchHeaders(nsIURI* aURI,
bool* aHeaderVal) {
if (!(mozilla::AndroidBridge::Bridge())) {
return false;
}
if (!aURI->SchemeIs("https")) {
return false;
}
// We need to improve below logic for matching google domains
// See Bug 1894642
// Is URI same as google ^https://www\\.google\\..+
nsAutoCString host;
aURI->GetHost(host);
LOG(("nsIOService::ShouldAddAdditionalSearchHeaders() checking host %s\n",
PromiseFlatCString(host).get()));
std::regex pattern("^www\\.google\\..+");
if (std::regex_match(host.get(), pattern)) {
LOG(("Google domain detected for host %s\n",
PromiseFlatCString(host).get()));
static bool ramAboveThreshold =
java::GeckoAppShell::IsDeviceRamThresholdOkay();
*aHeaderVal = ramAboveThreshold;
return true;
}
return false;
}
#endif
// static
void nsIOService::OnTLSPrefChange(const char* aPref, void* aSelf) {
MOZ_ASSERT(IsSocketProcessChild());
if (!EnsureNSSInitializedChromeOrContent()) {
LOG(("NSS not initialized."));
return;
}
nsAutoCString pref(aPref);
// The preferences listed in gCallbackSecurityPrefs need to be in sync with
// the code in HandleTLSPrefChange().
if (HandleTLSPrefChange(pref)) {
LOG(("HandleTLSPrefChange done"));
}
}
nsresult nsIOService::InitializeCaptivePortalService() {
if (XRE_GetProcessType() != GeckoProcessType_Default) {
// We only initalize a captive portal service in the main process
return NS_OK;
}
mCaptivePortalService = mozilla::components::CaptivePortal::Service();
if (mCaptivePortalService) {
static_cast<CaptivePortalService*>(mCaptivePortalService.get())
->Initialize();
}
// Instantiate and initialize the service
RefPtr<NetworkConnectivityService> ncs =
NetworkConnectivityService::GetSingleton();
return NS_OK;
}
nsresult nsIOService::InitializeSocketTransportService() {
nsresult rv = NS_OK;
if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed)) {
LOG(
("nsIOService aborting InitializeSocketTransportService because of app "
"shutdown"));
return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
}
if (!mSocketTransportService) {
mSocketTransportService =
mozilla::components::SocketTransport::Service(&rv);
if (NS_FAILED(rv)) {
NS_WARNING("failed to get socket transport service");
}
}
if (mSocketTransportService) {
rv = mSocketTransportService->Init();
NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service init failed");
mSocketTransportService->SetOffline(false);
}
return rv;
}
nsresult nsIOService::InitializeNetworkLinkService() {
nsresult rv = NS_OK;
if (mNetworkLinkServiceInitialized) return rv;
if (!NS_IsMainThread()) {
NS_WARNING("Network link service should be created on main thread");
return NS_ERROR_FAILURE;
}
// go into managed mode if we can, and chrome process
if (!XRE_IsParentProcess()) {
return NS_ERROR_NOT_AVAILABLE;
}
mNetworkLinkService = do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID, &rv);
if (mNetworkLinkService) {
mNetworkLinkServiceInitialized = true;
}
// After initializing the networkLinkService, query the connectivity state
OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN);
return rv;
}
nsresult nsIOService::InitializeProtocolProxyService() {
nsresult rv = NS_OK;
if (XRE_IsParentProcess()) {
// for early-initialization
Unused << mozilla::components::ProtocolProxy::Service(&rv);
}
return rv;
}
already_AddRefed<nsIOService> nsIOService::GetInstance() {
if (!gIOService) {
RefPtr<nsIOService> ios = new nsIOService();
if (NS_SUCCEEDED(ios->Init())) {
MOZ_ASSERT(gIOService == ios.get());
return ios.forget();
}
}
return do_AddRef(gIOService);
}
class SocketProcessListenerProxy : public SocketProcessHost::Listener {
public:
SocketProcessListenerProxy() = default;
void OnProcessLaunchComplete(SocketProcessHost* aHost, bool aSucceeded) {
if (!gIOService) {
return;
}
gIOService->OnProcessLaunchComplete(aHost, aSucceeded);
}
void OnProcessUnexpectedShutdown(SocketProcessHost* aHost) {
if (!gIOService) {
return;
}
gIOService->OnProcessUnexpectedShutdown(aHost);
}
};
// static
bool nsIOService::TooManySocketProcessCrash() {
return sSocketProcessCrashedCount >=
StaticPrefs::network_max_socket_process_failed_count();
}
// static
void nsIOService::IncreaseSocketProcessCrashCount() {
MOZ_ASSERT(IsNeckoChild());
sSocketProcessCrashedCount++;
}
nsresult nsIOService::LaunchSocketProcess() {
MOZ_ASSERT(NS_IsMainThread());
if (XRE_GetProcessType() != GeckoProcessType_Default) {
return NS_OK;
}
// We shouldn't launch socket prcess when shutdown begins.
if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed)) {
return NS_OK;
}
if (mSocketProcess) {
return NS_OK;
}
if (PR_GetEnv("MOZ_DISABLE_SOCKET_PROCESS")) {
LOG(("nsIOService skipping LaunchSocketProcess because of the env"));
return NS_OK;
}
if (!StaticPrefs::network_process_enabled()) {
LOG(("nsIOService skipping LaunchSocketProcess because of the pref"));
return NS_OK;
}
Preferences::RegisterPrefixCallbacks(
nsIOService::NotifySocketProcessPrefsChanged,
gCallbackPrefsForSocketProcess, this);
// The subprocess is launched asynchronously, so we wait for a callback to
// acquire the IPDL actor.
mSocketProcess = new SocketProcessHost(new SocketProcessListenerProxy());
LOG(("nsIOService::LaunchSocketProcess"));
if (!mSocketProcess->Launch()) {
NS_WARNING("Failed to launch socket process!!");
DestroySocketProcess();
return NS_ERROR_FAILURE;
}
return NS_OK;
}
void nsIOService::DestroySocketProcess() {
LOG(("nsIOService::DestroySocketProcess"));
MOZ_ASSERT(NS_IsMainThread());
if (XRE_GetProcessType() != GeckoProcessType_Default || !mSocketProcess) {
return;
}
Preferences::UnregisterPrefixCallbacks(
nsIOService::NotifySocketProcessPrefsChanged,
gCallbackPrefsForSocketProcess, this);
mSocketProcess->Shutdown();
mSocketProcess = nullptr;
}
bool nsIOService::SocketProcessReady() {
return mSocketProcess && mSocketProcess->IsConnected();
}
static bool sUseSocketProcess = false;
static bool sUseSocketProcessChecked = false;
// static
bool nsIOService::UseSocketProcess(bool aCheckAgain) {
if (sUseSocketProcessChecked && !aCheckAgain) {
return sUseSocketProcess;
}
sUseSocketProcessChecked = true;
sUseSocketProcess = false;
if (PR_GetEnv("MOZ_DISABLE_SOCKET_PROCESS")) {
return sUseSocketProcess;
}
if (TooManySocketProcessCrash()) {
LOG(("TooManySocketProcessCrash"));
return sUseSocketProcess;
}
if (PR_GetEnv("MOZ_FORCE_USE_SOCKET_PROCESS")) {
sUseSocketProcess = true;
return sUseSocketProcess;
}
if (StaticPrefs::network_process_enabled()) {
sUseSocketProcess =
StaticPrefs::network_http_network_access_on_socket_process_enabled();
}
return sUseSocketProcess;
}
// static
void nsIOService::NotifySocketProcessPrefsChanged(const char* aName,
void* aSelf) {
static_cast<nsIOService*>(aSelf)->NotifySocketProcessPrefsChanged(aName);
}
void nsIOService::NotifySocketProcessPrefsChanged(const char* aName) {
MOZ_ASSERT(NS_IsMainThread());
if (!XRE_IsParentProcess()) {
return;
}
if (!StaticPrefs::network_process_enabled()) {
return;
}
dom::Pref pref(nsCString(aName), /* isLocked */ false,
/* isSanitized */ false, Nothing(), Nothing());
Preferences::GetPreference(&pref, GeckoProcessType_Socket,
/* remoteType */ ""_ns);
auto sendPrefUpdate = [pref]() {
Unused << gIOService->mSocketProcess->GetActor()->SendPreferenceUpdate(
pref);
};
CallOrWaitForSocketProcess(sendPrefUpdate);
}
void nsIOService::OnProcessLaunchComplete(SocketProcessHost* aHost,
bool aSucceeded) {
MOZ_ASSERT(NS_IsMainThread());
LOG(("nsIOService::OnProcessLaunchComplete aSucceeded=%d\n", aSucceeded));
mSocketProcessLaunchComplete = aSucceeded;
if (mShutdown || !SocketProcessReady() || !aSucceeded) {
mPendingEvents.Clear();
return;
}
if (!mPendingEvents.IsEmpty()) {
nsTArray<std::function<void()>> pendingEvents = std::move(mPendingEvents);
for (auto& func : pendingEvents) {
func();
}
}
}
void nsIOService::CallOrWaitForSocketProcess(
const std::function<void()>& aFunc) {
MOZ_ASSERT(NS_IsMainThread());
if (IsSocketProcessLaunchComplete() && SocketProcessReady()) {
aFunc();
} else {
mPendingEvents.AppendElement(aFunc); // infallible
LaunchSocketProcess();
}
}
int32_t nsIOService::SocketProcessPid() {
if (!mSocketProcess) {
return 0;
}
if (SocketProcessParent* actor = mSocketProcess->GetActor()) {
return (int32_t)actor->OtherPid();
}
return 0;
}
bool nsIOService::IsSocketProcessLaunchComplete() {
MOZ_ASSERT(NS_IsMainThread());
return mSocketProcessLaunchComplete;
}
void nsIOService::OnProcessUnexpectedShutdown(SocketProcessHost* aHost) {
MOZ_ASSERT(NS_IsMainThread());
LOG(("nsIOService::OnProcessUnexpectedShutdown\n"));
DestroySocketProcess();
mPendingEvents.Clear();
// Nothing to do if socket process was not used before.
if (!UseSocketProcess()) {
return;
}
sSocketProcessCrashedCount++;
if (TooManySocketProcessCrash()) {
sUseSocketProcessChecked = false;
DNSServiceWrapper::SwitchToBackupDNSService();
}
nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
if (observerService) {
(void)observerService->NotifyObservers(
nullptr, "network:socket-process-crashed", nullptr);
}
// UseSocketProcess() could return false if we have too many crashes, so we
// should call it again.
if (UseSocketProcess()) {
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
NewRunnableMethod("nsIOService::LaunchSocketProcess", this,
&nsIOService::LaunchSocketProcess)));
}
}
RefPtr<MemoryReportingProcess> nsIOService::GetSocketProcessMemoryReporter() {
// Check the prefs here again, since we don't want to create
// SocketProcessMemoryReporter for some tests.
if (!StaticPrefs::network_process_enabled() || !SocketProcessReady()) {
return nullptr;
}
return new SocketProcessMemoryReporter();
}
NS_IMETHODIMP
nsIOService::SocketProcessTelemetryPing() {
CallOrWaitForSocketProcess([]() {
Unused << gIOService->mSocketProcess->GetActor()
->SendSocketProcessTelemetryPing();
});
return NS_OK;
}
NS_IMPL_ISUPPORTS(nsIOService, nsIIOService, nsINetUtil, nsISpeculativeConnect,
nsIObserver, nsIIOServiceInternal, nsISupportsWeakReference,
nsIObserverService)
////////////////////////////////////////////////////////////////////////////////
nsresult nsIOService::RecheckCaptivePortal() {
MOZ_ASSERT(NS_IsMainThread(), "Must be called on the main thread");
if (!mCaptivePortalService) {
return NS_OK;
}
nsCOMPtr<nsIRunnable> task = NewRunnableMethod(
"nsIOService::RecheckCaptivePortal", mCaptivePortalService,
&nsICaptivePortalService::RecheckCaptivePortal);
return NS_DispatchToMainThread(task);
}
nsresult nsIOService::RecheckCaptivePortalIfLocalRedirect(nsIChannel* newChan) {
nsresult rv;
if (!mCaptivePortalService) {
return NS_OK;
}
nsCOMPtr<nsIURI> uri;
rv = newChan->GetURI(getter_AddRefs(uri));
if (NS_FAILED(rv)) {
return rv;
}
nsCString host;
rv = uri->GetHost(host);
if (NS_FAILED(rv)) {
return rv;
}
NetAddr addr;
// If the redirect wasn't to an IP literal, so there's probably no need
// to trigger the captive portal detection right now. It can wait.
if (NS_SUCCEEDED(addr.InitFromString(host)) && addr.IsIPAddrLocal()) {
RecheckCaptivePortal();
}
return NS_OK;
}
nsresult nsIOService::AsyncOnChannelRedirect(
nsIChannel* oldChan, nsIChannel* newChan, uint32_t flags,
nsAsyncRedirectVerifyHelper* helper) {
// If a redirect to a local network address occurs, then chances are we
// are in a captive portal, so we trigger a recheck.
RecheckCaptivePortalIfLocalRedirect(newChan);
// This is silly. I wish there was a simpler way to get at the global
// reference of the contentSecurityManager. But it lives in the XPCOM
// service registry.
nsCOMPtr<nsIChannelEventSink> sink;
sink = mozilla::components::ContentSecurityManager::Service();
if (sink) {
nsresult rv =
helper->DelegateOnChannelRedirect(sink, oldChan, newChan, flags);
if (NS_FAILED(rv)) return rv;
}
// Finally, our category
nsCOMArray<nsIChannelEventSink> entries;
mChannelEventSinks.GetEntries(entries);
int32_t len = entries.Count();
for (int32_t i = 0; i < len; ++i) {
nsresult rv =
helper->DelegateOnChannelRedirect(entries[i], oldChan, newChan, flags);
if (NS_FAILED(rv)) return rv;
}
nsCOMPtr<nsIHttpChannel> httpChan(do_QueryInterface(oldChan));
// Collect the redirection from HTTP(S) only.
if (httpChan) {
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIURI> newURI;
newChan->GetURI(getter_AddRefs(newURI));
MOZ_ASSERT(newURI);
nsAutoCString scheme;
newURI->GetScheme(scheme);
MOZ_ASSERT(!scheme.IsEmpty());
if (oldChan->IsDocument()) {
Telemetry::AccumulateCategoricalKeyed(
scheme, Telemetry::LABELS_NETWORK_HTTP_REDIRECT_TO_SCHEME::topLevel);
#ifndef ANDROID
mozilla::glean::networking::http_redirect_to_scheme_top_level.Get(scheme)
.Add(1);
#endif
} else {
Telemetry::AccumulateCategoricalKeyed(
scheme,
Telemetry::LABELS_NETWORK_HTTP_REDIRECT_TO_SCHEME::subresource);
#ifndef ANDROID
mozilla::glean::networking::http_redirect_to_scheme_subresource
.Get(scheme)
.Add(1);
#endif
}
}
return NS_OK;
}
bool nsIOService::UsesExternalProtocolHandler(const nsACString& aScheme) {
if (aScheme == "file"_ns || aScheme == "chrome"_ns ||
aScheme == "resource"_ns) {
// Don't allow file:, chrome: or resource: URIs to be handled with
// nsExternalProtocolHandler, since internally we rely on being able to
// use and read from these URIs.
return false;
}
if (aScheme == "place"_ns || aScheme == "fake-favicon-uri"_ns ||
aScheme == "favicon"_ns || aScheme == "moz-nullprincipal"_ns) {
// Force place: fake-favicon-uri: favicon: and moz-nullprincipal: URIs to be
// handled with nsExternalProtocolHandler, and not with a dynamically
// registered handler.
return true;
}
// If prefs configure the URI to be handled externally, do so.
for (const auto& scheme : mForceExternalSchemes) {
if (aScheme == scheme) {
return true;
}
}
return false;
}
ProtocolHandlerInfo nsIOService::LookupProtocolHandler(
const nsACString& aScheme) {
// Look-ups are ASCII-case-insensitive, so lower-case the string before
// continuing.
nsAutoCString scheme(aScheme);
ToLowerCase(scheme);
// NOTE: If we could get rid of mForceExternalSchemes (or prevent them from
// disabling static protocols), we could avoid locking mLock until we need to
// check `mRuntimeProtocolHandlers.
AutoReadLock lock(mLock);
if (!UsesExternalProtocolHandler(scheme)) {
// Try the static protocol handler first - they cannot be overridden by
// dynamic protocols.
if (const xpcom::StaticProtocolHandler* handler =
xpcom::StaticProtocolHandler::Lookup(scheme)) {
return ProtocolHandlerInfo(*handler);
}
if (auto handler = mRuntimeProtocolHandlers.Lookup(scheme)) {
return ProtocolHandlerInfo(handler.Data());
}
}
return ProtocolHandlerInfo(xpcom::StaticProtocolHandler::Default());
}
NS_IMETHODIMP
nsIOService::GetProtocolHandler(const char* scheme,
nsIProtocolHandler** result) {
AssertIsOnMainThread();
NS_ENSURE_ARG_POINTER(scheme);
*result = LookupProtocolHandler(nsDependentCString(scheme)).Handler().take();
return *result ? NS_OK : NS_ERROR_UNKNOWN_PROTOCOL;
}
NS_IMETHODIMP
nsIOService::ExtractScheme(const nsACString& inURI, nsACString& scheme) {
return net_ExtractURLScheme(inURI, scheme);
}
NS_IMETHODIMP
nsIOService::HostnameIsLocalIPAddress(nsIURI* aURI, bool* aResult) {
NS_ENSURE_ARG_POINTER(aURI);
nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aURI);
NS_ENSURE_ARG_POINTER(innerURI);
nsAutoCString host;
nsresult rv = innerURI->GetAsciiHost(host);
if (NS_FAILED(rv)) {
return rv;
}
*aResult = false;
NetAddr addr;
if (NS_SUCCEEDED(addr.InitFromString(host)) && addr.IsIPAddrLocal()) {
*aResult = true;
}
return NS_OK;
}
NS_IMETHODIMP
nsIOService::HostnameIsSharedIPAddress(nsIURI* aURI, bool* aResult) {
NS_ENSURE_ARG_POINTER(aURI);
nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aURI);
NS_ENSURE_ARG_POINTER(innerURI);
nsAutoCString host;
nsresult rv = innerURI->GetAsciiHost(host);
if (NS_FAILED(rv)) {
return rv;
}
*aResult = false;
NetAddr addr;
if (NS_SUCCEEDED(addr.InitFromString(host)) && addr.IsIPAddrShared()) {
*aResult = true;
}
return NS_OK;
}
NS_IMETHODIMP
nsIOService::IsValidHostname(const nsACString& inHostname, bool* aResult) {
if (!net_IsValidDNSHost(inHostname)) {
*aResult = false;
return NS_OK;
}
// hostname ending with a "." delimited octet that is a number
// must be IPv4 or IPv6 dual address
nsAutoCString host(inHostname);
if (IPv4Parser::EndsInANumber(host)) {
// ipv6 dual address; for example "::1.2.3.4"
if (net_IsValidIPv6Addr(host)) {
*aResult = true;
return NS_OK;
}
nsAutoCString normalized;
nsresult rv = IPv4Parser::NormalizeIPv4(host, normalized);
if (NS_FAILED(rv)) {
*aResult = false;
return NS_OK;
}
}
*aResult = true;
return NS_OK;
}
NS_IMETHODIMP
nsIOService::GetProtocolFlags(const char* scheme, uint32_t* flags) {
NS_ENSURE_ARG_POINTER(scheme);
*flags =
LookupProtocolHandler(nsDependentCString(scheme)).StaticProtocolFlags();
return NS_OK;
}
NS_IMETHODIMP
nsIOService::GetDynamicProtocolFlags(nsIURI* uri, uint32_t* flags) {
AssertIsOnMainThread();
NS_ENSURE_ARG(uri);
nsAutoCString scheme;
nsresult rv = uri->GetScheme(scheme);
NS_ENSURE_SUCCESS(rv, rv);
return LookupProtocolHandler(scheme).DynamicProtocolFlags(uri, flags);
}
NS_IMETHODIMP
nsIOService::GetDefaultPort(const char* scheme, int32_t* defaultPort) {
NS_ENSURE_ARG_POINTER(scheme);
*defaultPort =
LookupProtocolHandler(nsDependentCString(scheme)).DefaultPort();
return NS_OK;
}
nsresult nsIOService::NewURI(const nsACString& aSpec, const char* aCharset,
nsIURI* aBaseURI, nsIURI** result) {
return NS_NewURI(result, aSpec, aCharset, aBaseURI);
}
NS_IMETHODIMP
nsIOService::NewFileURI(nsIFile* file, nsIURI** result) {
nsresult rv;
NS_ENSURE_ARG_POINTER(file);
nsCOMPtr<nsIProtocolHandler> handler;
rv = GetProtocolHandler("file", getter_AddRefs(handler));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIFileProtocolHandler> fileHandler(do_QueryInterface(handler, &rv));
if (NS_FAILED(rv)) return rv;
return fileHandler->NewFileURI(file, result);
}
// static
already_AddRefed<nsIURI> nsIOService::CreateExposableURI(nsIURI* aURI) {
MOZ_ASSERT(aURI, "Must have a URI");
nsCOMPtr<nsIURI> uri = aURI;
bool hasUserPass;
if (NS_SUCCEEDED(aURI->GetHasUserPass(&hasUserPass)) && hasUserPass) {
DebugOnly<nsresult> rv = NS_MutateURI(uri).SetUserPass(""_ns).Finalize(uri);
MOZ_ASSERT(NS_SUCCEEDED(rv) && uri, "Mutating URI should never fail");
}
return uri.forget();
}
NS_IMETHODIMP
nsIOService::CreateExposableURI(nsIURI* aURI, nsIURI** _result) {
NS_ENSURE_ARG_POINTER(aURI);
NS_ENSURE_ARG_POINTER(_result);
nsCOMPtr<nsIURI> exposableURI = CreateExposableURI(aURI);
exposableURI.forget(_result);
return NS_OK;
}
NS_IMETHODIMP
nsIOService::NewChannelFromURI(nsIURI* aURI, nsINode* aLoadingNode,
nsIPrincipal* aLoadingPrincipal,
nsIPrincipal* aTriggeringPrincipal,
uint32_t aSecurityFlags,
nsContentPolicyType aContentPolicyType,
nsIChannel** result) {
return NewChannelFromURIWithProxyFlags(aURI,
nullptr, // aProxyURI
0, // aProxyFlags
aLoadingNode, aLoadingPrincipal,
aTriggeringPrincipal, aSecurityFlags,
aContentPolicyType, result);
}
nsresult nsIOService::NewChannelFromURIWithClientAndController(
nsIURI* aURI, nsINode* aLoadingNode, nsIPrincipal* aLoadingPrincipal,
nsIPrincipal* aTriggeringPrincipal,
const Maybe<ClientInfo>& aLoadingClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController, uint32_t aSecurityFlags,
nsContentPolicyType aContentPolicyType, uint32_t aSandboxFlags,
bool aSkipCheckForBrokenURLOrZeroSized, nsIChannel** aResult) {
return NewChannelFromURIWithProxyFlagsInternal(
aURI,
nullptr, // aProxyURI
0, // aProxyFlags
aLoadingNode, aLoadingPrincipal, aTriggeringPrincipal, aLoadingClientInfo,
aController, aSecurityFlags, aContentPolicyType, aSandboxFlags,
aSkipCheckForBrokenURLOrZeroSized, aResult);
}
NS_IMETHODIMP
nsIOService::NewChannelFromURIWithLoadInfo(nsIURI* aURI, nsILoadInfo* aLoadInfo,
nsIChannel** result) {
return NewChannelFromURIWithProxyFlagsInternal(aURI,
nullptr, // aProxyURI
0, // aProxyFlags
aLoadInfo, result);
}
nsresult nsIOService::NewChannelFromURIWithProxyFlagsInternal(
nsIURI* aURI, nsIURI* aProxyURI, uint32_t aProxyFlags,
nsINode* aLoadingNode, nsIPrincipal* aLoadingPrincipal,
nsIPrincipal* aTriggeringPrincipal,
const Maybe<ClientInfo>& aLoadingClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController, uint32_t aSecurityFlags,
nsContentPolicyType aContentPolicyType, uint32_t aSandboxFlags,
bool aSkipCheckForBrokenURLOrZeroSized, nsIChannel** result) {
nsCOMPtr<nsILoadInfo> loadInfo = new LoadInfo(
aLoadingPrincipal, aTriggeringPrincipal, aLoadingNode, aSecurityFlags,
aContentPolicyType, aLoadingClientInfo, aController, aSandboxFlags,
aSkipCheckForBrokenURLOrZeroSized);
return NewChannelFromURIWithProxyFlagsInternal(aURI, aProxyURI, aProxyFlags,
loadInfo, result);
}
nsresult nsIOService::NewChannelFromURIWithProxyFlagsInternal(
nsIURI* aURI, nsIURI* aProxyURI, uint32_t aProxyFlags,
nsILoadInfo* aLoadInfo, nsIChannel** result) {
nsresult rv;
NS_ENSURE_ARG_POINTER(aURI);
// all channel creations must provide a valid loadinfo