Files
palemoon27/dom/html/nsHTMLDNSPrefetch.cpp
T
roytam1 4a4a995d26 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1240330 - mozAlarm debug messages are turned on r=khuey (aa938a4371)
- fix (cdc44e8bc8)
- Bug 1239788 - Don't include non-main-thread assertions in the constructor enabled check for [Exposed=System] WebIDL interfaces; r=bzbarsky (5d05b4066a)
- Bug 1247346. Slot indices on IDL interface members that get a slot should be per-interface, not a single per-member number. r=peterv (640231c37e)
- Bug 1157469 - null check wrapper in case WrapNode fails, r=bholley (9fd9b038db)
- Bug 1242211 - Mark MozMapRooter as final; r=baku (f3b5cc7728)
- Bug 1243438. Don't try to include the filename '<unknown>' when including headers for unions that have a built-in typedef they're referenced by. r=peterv (781d1ec0af)
- Bug 1241021 part 1: Refactor GenerateCSS2PropertiesWebIDL.py to invoke a helper function for each line. r=bz (258b031fd8)
- Bug 1241021 part 2: Make GenerateCSS2PropertiesWebIDL.py produce capitalized as well as uncapitalized WebkitFoo/webkitFoo DOM style accessors. r=bz (0bf2ec95ae)
- Bug 1241021 part 3: Refactor CSS mochitest test_initial_storage.html to perform its DOM accessor consistency-checks via a helper-function. r=bz (3a0c1a1678)
- Bug 1241021 part 4: Extend mochitest test_initial_storage.html to test that uppercase Webkit DOM accessors for css properties are functional. r=bz (5a6a23c7ab)
- Bug 1240592 - Remove unnecessary -Wno-uninitialized from dom/bindings. r=khuey (c854f7b397)
- Bug 1200341 - Implement HKDF for WebCrypto r=rbarnes,smaug (2c830d65a1)
- Bug 1200341 - Use BufferSource instead of CryptoOperationData in the SubtleCrypto WebIDL spec r=smaug (8cece95b5c)
- Bug 1191936 - Implement RSA-PSS key generation r=rbarnes (ec9654595c)
- Bug 1191936 - Implement RSA-PSS signing and verification r=rbarnes,smaug (7653bdfced)
- Bug 1204763 follow-up: Fix the comments, DONTBUILD (8b26e6f3a9)
- Reformat clang-plugin.cpp using clang-format, no bug (9346eda9f4)
- Bug 1214037 - Don't consider the result of an assignment expression MOZ_MUST_USE, r=ehsan (70c7830c3a)
- Bug 1242789 - Allow lambdas to capture raw pointers to refcounted objects by reference, r=ehsan (e7158a7746)
- Bug 1238042 - Add about:checkerboard. r=ehsan,botond (f234ce7fa0)
- Bug 1237177. Make the this-rebinding callable proxy sandboxes use return the prototype of its target, not its own null prototype. r=efaust (694a8081dc)
- Bug 1248521 - Pack PrefHashEntry better. r=froydnj. (55e9d609fe)
- Bug 1240453 - enable shared memory in xpconnect. r=bz (58db0b406e)
- Bug 1202014 - Don't use-after-move in ActorsChild.cpp, r=khuey (382e7183c0)
- Bug 1136762 - TSan: data race xpcom/io/nsPipe3.cpp:1061 CloseWithStatus. r=nfroyd. (68fd82971d)
- Bug 1237668 - Remove nsSimpleUnicharStreamFactory r=froydnj (8bb6ec081c)
- Bug 1234012 - Remove the NS_APP_PROFILE_DEFAULTS_{NLOC_,}50_DIR directory keys. r=bsmedberg (386f5b22ff)
- Bug 1235099 - Remove the NS_APP_BOOKMARKS_50_FILE directory service key. r=dolske (a46afe7211)
- Bug 1189998, Part 4 - Add authentication secret to Push data test. r=dragana (122a0bd5f9)
- Bug 1205137 - Add a PushSubscription serializer. r=mt,smaug (aa9e847c42)
- Bug 1232910 - Use channel.asyncOpen2 within dom/push/PushServiceHttp2.jsm. r=sicking r=dragana (a2f483a983)
- Bug 1246632 - Fix ackMsgRecv in PushServiceHttp2.js. r=kitcambridge (c1559e0539)
- Bug 1240615 - Make PushService protocol init method return a Promise. r=kitcambridge (4d52dc6a41)
- Bug 1211160 - update lastModifiedTime of distribution addons to properly sync roaming profiles, r=dtownsend (ae73a213b8)
- Bug 1232222 - expose isSystem flag if add-on is a system add-on r=Mossop (f057a5c375)
- Bug 1167627 - Part 9: Use mozinfo in services/. r=rnewman (5312e35c13)
- Bug 1205620 - fix default visibility of warning/error buttons in addon manager, r=Mossop (b071fc5cef)
- Bug 1237820: Track whether a user has been offered a sideloaded add-on or not. r=rhelmer (26ca999e3b)
- Bug 1236377: Ignore invalid file descriptors when loading an add-ons database written by a different OS. r=rhelmer (b78f0f5342)
- Bug 1246245 - Webextensions and themes should also block initial e10s rollout. r=Mossop (d4cd588b16)
- Bug 1245916: Turn on no-undef in toolkit/mozapps/extensions. r=rhelmer (4a9d16eff6)
- Bug 1245251 - Repair add-on manager for external XUL apps. r=Mossop (4e525d634c)
- Bug 1244302: Remove the add-ons selection UI. (981e4deaf3)
- Bug 1243935 - "Restartless add-ons that get into the pending disable state never disable". r=aswan (7b320b3930)
- Bug 612168 - Handle uninstalls of restartless addons in XPIProvider. r=Mossop (48943f830a)
- Bug 1239484 - remove use of Object.values() r=mossop (57f9a179bc)
- Bug 1246784 - Expose Console to the WorkerDebuggerGlobalScope, r=khuey (a992fdc555)
- misspatch (33708903c4)
- Bug 1207494 - Part 5: Remove use of expression closure from dom/contacts/. r=reuben (256b3831a4)
- Bug 1207494 - Part 4: Remove use of expression closure from dom/canvas/. r=gw280 (1666e49673)
- Bug 1207494 - Part 3: Remove use of expression closure from dom/browser-element/. r=smaug (a891769373)
- Bug 1207494 - Part 2: Remove use of expression closure from dom/base/test/. r=peterv (01762e3181)
- Bug 1207494 - Part 1: Remove use of expression closure from dom/apps/. r=ferjm (2474c8619b)
- Bug 1247108 - Pass securityFlag when creating a new channel within webapps (r=fabrice) (8305294f26)
- Bug 1219004 - Improve error management in getFullAppByManifestURL r=ferjm (c3ad64df7a)
- revert contains/includes (29c60a77e5)
- Bug 1147562 - Update remaining callsites of newChannel before landing the shim in dom/ (r=sicking) (0cd64e20e1)
- Bug 1243924 - Convert remaining callsites within dom/ to use channel.open2() (r=sicking) (43b01f88ba)
- Bug 1162658 - Update FormData to match latest spec, r=smaug (a42ca52ad5)
- Bug 1208895 - Fix a typo in nsGenericHTMLElement::GetItemId(); r=baku (2d6f2d79f4)
- Bug 1223523. The named getter on document should not return images with an empty name. r=peterv (da3d1f52f5)
- Bug 1183491. Null-check the document we get from our contentWindow in the contentDocument getter, because apparently it can end up null. r=bkelly (3002a4375c)
- Bug 1203430 - Intermittent crash in PNeckoChild::SendHTMLDNSPrefetch. r=jdm (3b82b57cbf)
- Bug 893332, part 1 - Rename misnamed SetValidityState/GetValidityState arguments. r=baku (d403b12c9a)
- Bug 893332, part 2 - Update validity state before asserting range underflow state. r=baku (a4cbce224c)
- Bug 893332, part 3 - Don't assert range underflow state under the parser. r=baku (763e99ed8e)
- Bug 893332, part 4 - Crashtests. r=baku (7cdcdc02c4)
- Bug 1240336 Setting same value to either <input> or <textarea> shouldn't cause committing existing composition r=ehsan (5cc2c35dbb)
- Bug 1228708. Fix UndoManager to correctly suppress exceptions it wants to suppress on ErrorResults. r=smaug (905207a3b4)
- Bug 1230295 - Add telemetry to report when Ogg chaining is used. r=rillian,r=vladan (e47c49f508)
2023-12-29 15:55:20 +08:00

479 lines
14 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 "base/basictypes.h"
#include "mozilla/net/NeckoCommon.h"
#include "mozilla/net/NeckoChild.h"
#include "nsURLHelper.h"
#include "nsHTMLDNSPrefetch.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsIProtocolHandler.h"
#include "nsIDNSListener.h"
#include "nsIWebProgressListener.h"
#include "nsIWebProgress.h"
#include "nsCURILoader.h"
#include "nsIDNSRecord.h"
#include "nsIDNSService.h"
#include "nsICancelable.h"
#include "nsGkAtoms.h"
#include "nsIDocument.h"
#include "nsThreadUtils.h"
#include "nsITimer.h"
#include "nsIObserverService.h"
#include "mozilla/dom/Link.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::net;
static NS_DEFINE_CID(kDNSServiceCID, NS_DNSSERVICE_CID);
bool sDisablePrefetchHTTPSPref;
static bool sInitialized = false;
static nsIDNSService *sDNSService = nullptr;
static nsHTMLDNSPrefetch::nsDeferrals *sPrefetches = nullptr;
static nsHTMLDNSPrefetch::nsListener *sDNSListener = nullptr;
nsresult
nsHTMLDNSPrefetch::Initialize()
{
if (sInitialized) {
NS_WARNING("Initialize() called twice");
return NS_OK;
}
sPrefetches = new nsHTMLDNSPrefetch::nsDeferrals();
NS_ADDREF(sPrefetches);
sDNSListener = new nsHTMLDNSPrefetch::nsListener();
NS_ADDREF(sDNSListener);
sPrefetches->Activate();
Preferences::AddBoolVarCache(&sDisablePrefetchHTTPSPref,
"network.dns.disablePrefetchFromHTTPS");
// Default is false, so we need an explicit call to prime the cache.
sDisablePrefetchHTTPSPref =
Preferences::GetBool("network.dns.disablePrefetchFromHTTPS", true);
NS_IF_RELEASE(sDNSService);
nsresult rv;
rv = CallGetService(kDNSServiceCID, &sDNSService);
if (NS_FAILED(rv)) return rv;
if (IsNeckoChild())
NeckoChild::InitNeckoChild();
sInitialized = true;
return NS_OK;
}
nsresult
nsHTMLDNSPrefetch::Shutdown()
{
if (!sInitialized) {
NS_WARNING("Not Initialized");
return NS_OK;
}
sInitialized = false;
NS_IF_RELEASE(sDNSService);
NS_IF_RELEASE(sPrefetches);
NS_IF_RELEASE(sDNSListener);
return NS_OK;
}
bool
nsHTMLDNSPrefetch::IsAllowed (nsIDocument *aDocument)
{
if (NS_IsAppOffline(aDocument->NodePrincipal())) {
return false;
}
// There is no need to do prefetch on non UI scenarios such as XMLHttpRequest.
return aDocument->IsDNSPrefetchAllowed() && aDocument->GetWindow();
}
nsresult
nsHTMLDNSPrefetch::Prefetch(Link *aElement, uint16_t flags)
{
if (!(sInitialized && sPrefetches && sDNSService && sDNSListener))
return NS_ERROR_NOT_AVAILABLE;
return sPrefetches->Add(flags, aElement);
}
nsresult
nsHTMLDNSPrefetch::PrefetchLow(Link *aElement)
{
return Prefetch(aElement, nsIDNSService::RESOLVE_PRIORITY_LOW);
}
nsresult
nsHTMLDNSPrefetch::PrefetchMedium(Link *aElement)
{
return Prefetch(aElement, nsIDNSService::RESOLVE_PRIORITY_MEDIUM);
}
nsresult
nsHTMLDNSPrefetch::PrefetchHigh(Link *aElement)
{
return Prefetch(aElement, 0);
}
nsresult
nsHTMLDNSPrefetch::Prefetch(const nsAString &hostname, uint16_t flags)
{
if (IsNeckoChild()) {
// We need to check IsEmpty() because net_IsValidHostName()
// considers empty strings to be valid hostnames
if (!hostname.IsEmpty() &&
net_IsValidHostName(NS_ConvertUTF16toUTF8(hostname))) {
// during shutdown gNeckoChild might be null
if (gNeckoChild) {
gNeckoChild->SendHTMLDNSPrefetch(nsAutoString(hostname), flags);
}
}
return NS_OK;
}
if (!(sInitialized && sDNSService && sPrefetches && sDNSListener))
return NS_ERROR_NOT_AVAILABLE;
nsCOMPtr<nsICancelable> tmpOutstanding;
return sDNSService->AsyncResolve(NS_ConvertUTF16toUTF8(hostname),
flags | nsIDNSService::RESOLVE_SPECULATE,
sDNSListener, nullptr,
getter_AddRefs(tmpOutstanding));
}
nsresult
nsHTMLDNSPrefetch::PrefetchLow(const nsAString &hostname)
{
return Prefetch(hostname, nsIDNSService::RESOLVE_PRIORITY_LOW);
}
nsresult
nsHTMLDNSPrefetch::PrefetchMedium(const nsAString &hostname)
{
return Prefetch(hostname, nsIDNSService::RESOLVE_PRIORITY_MEDIUM);
}
nsresult
nsHTMLDNSPrefetch::PrefetchHigh(const nsAString &hostname)
{
return Prefetch(hostname, 0);
}
nsresult
nsHTMLDNSPrefetch::CancelPrefetch(Link *aElement,
uint16_t flags,
nsresult aReason)
{
if (!(sInitialized && sPrefetches && sDNSService && sDNSListener))
return NS_ERROR_NOT_AVAILABLE;
nsAutoString hostname;
aElement->GetHostname(hostname);
return CancelPrefetch(hostname, flags, aReason);
}
nsresult
nsHTMLDNSPrefetch::CancelPrefetch(const nsAString &hostname,
uint16_t flags,
nsresult aReason)
{
// Forward this request to Necko Parent if we're a child process
if (IsNeckoChild()) {
// We need to check IsEmpty() because net_IsValidHostName()
// considers empty strings to be valid hostnames
if (!hostname.IsEmpty() &&
net_IsValidHostName(NS_ConvertUTF16toUTF8(hostname))) {
// during shutdown gNeckoChild might be null
if (gNeckoChild) {
gNeckoChild->SendCancelHTMLDNSPrefetch(nsString(hostname), flags,
aReason);
}
}
return NS_OK;
}
if (!(sInitialized && sDNSService && sPrefetches && sDNSListener))
return NS_ERROR_NOT_AVAILABLE;
// Forward cancellation to DNS service
return sDNSService->CancelAsyncResolve(NS_ConvertUTF16toUTF8(hostname),
flags
| nsIDNSService::RESOLVE_SPECULATE,
sDNSListener, aReason);
}
nsresult
nsHTMLDNSPrefetch::CancelPrefetchLow(Link *aElement, nsresult aReason)
{
return CancelPrefetch(aElement, nsIDNSService::RESOLVE_PRIORITY_LOW,
aReason);
}
nsresult
nsHTMLDNSPrefetch::CancelPrefetchLow(const nsAString &hostname, nsresult aReason)
{
return CancelPrefetch(hostname, nsIDNSService::RESOLVE_PRIORITY_LOW,
aReason);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
NS_IMPL_ISUPPORTS(nsHTMLDNSPrefetch::nsListener,
nsIDNSListener)
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsListener::OnLookupComplete(nsICancelable *request,
nsIDNSRecord *rec,
nsresult status)
{
return NS_OK;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
nsHTMLDNSPrefetch::nsDeferrals::nsDeferrals()
: mHead(0),
mTail(0),
mActiveLoaderCount(0),
mTimerArmed(false)
{
mTimer = do_CreateInstance("@mozilla.org/timer;1");
}
nsHTMLDNSPrefetch::nsDeferrals::~nsDeferrals()
{
if (mTimerArmed) {
mTimerArmed = false;
mTimer->Cancel();
}
Flush();
}
NS_IMPL_ISUPPORTS(nsHTMLDNSPrefetch::nsDeferrals,
nsIWebProgressListener,
nsISupportsWeakReference,
nsIObserver)
void
nsHTMLDNSPrefetch::nsDeferrals::Flush()
{
while (mHead != mTail) {
mEntries[mTail].mElement = nullptr;
mTail = (mTail + 1) & sMaxDeferredMask;
}
}
nsresult
nsHTMLDNSPrefetch::nsDeferrals::Add(uint16_t flags, Link *aElement)
{
// The FIFO has no lock, so it can only be accessed on main thread
NS_ASSERTION(NS_IsMainThread(), "nsDeferrals::Add must be on main thread");
aElement->OnDNSPrefetchDeferred();
if (((mHead + 1) & sMaxDeferredMask) == mTail)
return NS_ERROR_DNS_LOOKUP_QUEUE_FULL;
mEntries[mHead].mFlags = flags;
mEntries[mHead].mElement = do_GetWeakReference(aElement);
mHead = (mHead + 1) & sMaxDeferredMask;
if (!mActiveLoaderCount && !mTimerArmed && mTimer) {
mTimerArmed = true;
mTimer->InitWithFuncCallback(Tick, this, 2000, nsITimer::TYPE_ONE_SHOT);
}
return NS_OK;
}
void
nsHTMLDNSPrefetch::nsDeferrals::SubmitQueue()
{
NS_ASSERTION(NS_IsMainThread(), "nsDeferrals::SubmitQueue must be on main thread");
nsCString hostName;
if (!sDNSService) return;
while (mHead != mTail) {
nsCOMPtr<nsIContent> content = do_QueryReferent(mEntries[mTail].mElement);
if (content) {
nsCOMPtr<Link> link = do_QueryInterface(content);
// Only prefetch here if request was deferred and deferral not cancelled
if (link && link->HasDeferredDNSPrefetchRequest()) {
nsCOMPtr<nsIURI> hrefURI(link ? link->GetURI() : nullptr);
bool isLocalResource = false;
nsresult rv;
hostName.Truncate();
if (hrefURI) {
hrefURI->GetAsciiHost(hostName);
rv = NS_URIChainHasFlags(hrefURI,
nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
&isLocalResource);
}
if (!hostName.IsEmpty() && NS_SUCCEEDED(rv) && !isLocalResource) {
if (IsNeckoChild()) {
// during shutdown gNeckoChild might be null
if (gNeckoChild) {
gNeckoChild->SendHTMLDNSPrefetch(NS_ConvertUTF8toUTF16(hostName),
mEntries[mTail].mFlags);
}
} else {
nsCOMPtr<nsICancelable> tmpOutstanding;
rv = sDNSService->AsyncResolve(hostName,
mEntries[mTail].mFlags
| nsIDNSService::RESOLVE_SPECULATE,
sDNSListener, nullptr,
getter_AddRefs(tmpOutstanding));
// Tell link that deferred prefetch was requested
if (NS_SUCCEEDED(rv))
link->OnDNSPrefetchRequested();
}
}
}
}
mEntries[mTail].mElement = nullptr;
mTail = (mTail + 1) & sMaxDeferredMask;
}
if (mTimerArmed) {
mTimerArmed = false;
mTimer->Cancel();
}
}
void
nsHTMLDNSPrefetch::nsDeferrals::Activate()
{
// Register as an observer for the document loader
nsCOMPtr<nsIWebProgress> progress =
do_GetService(NS_DOCUMENTLOADER_SERVICE_CONTRACTID);
if (progress)
progress->AddProgressListener(this, nsIWebProgress::NOTIFY_STATE_DOCUMENT);
// Register as an observer for xpcom shutdown events so we can drop any element refs
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService)
observerService->AddObserver(this, "xpcom-shutdown", true);
}
// nsITimer related method
void
nsHTMLDNSPrefetch::nsDeferrals::Tick(nsITimer *aTimer, void *aClosure)
{
nsHTMLDNSPrefetch::nsDeferrals *self = (nsHTMLDNSPrefetch::nsDeferrals *) aClosure;
NS_ASSERTION(NS_IsMainThread(), "nsDeferrals::Tick must be on main thread");
NS_ASSERTION(self->mTimerArmed, "Timer is not armed");
self->mTimerArmed = false;
// If the queue is not submitted here because there are outstanding pages being loaded,
// there is no need to rearm the timer as the queue will be submtited when those
// loads complete.
if (!self->mActiveLoaderCount)
self->SubmitQueue();
}
//////////// nsIWebProgressListener methods
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsDeferrals::OnStateChange(nsIWebProgress* aWebProgress,
nsIRequest *aRequest,
uint32_t progressStateFlags,
nsresult aStatus)
{
// The FIFO has no lock, so it can only be accessed on main thread
NS_ASSERTION(NS_IsMainThread(), "nsDeferrals::OnStateChange must be on main thread");
if (progressStateFlags & STATE_IS_DOCUMENT) {
if (progressStateFlags & STATE_STOP) {
// Initialization may have missed a STATE_START notification, so do
// not go negative
if (mActiveLoaderCount)
mActiveLoaderCount--;
if (!mActiveLoaderCount)
SubmitQueue();
}
else if (progressStateFlags & STATE_START)
mActiveLoaderCount++;
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsDeferrals::OnProgressChange(nsIWebProgress *aProgress,
nsIRequest *aRequest,
int32_t curSelfProgress,
int32_t maxSelfProgress,
int32_t curTotalProgress,
int32_t maxTotalProgress)
{
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsDeferrals::OnLocationChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsIURI *location,
uint32_t aFlags)
{
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsDeferrals::OnStatusChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsresult aStatus,
const char16_t* aMessage)
{
return NS_OK;
}
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsDeferrals::OnSecurityChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
uint32_t state)
{
return NS_OK;
}
//////////// nsIObserver method
NS_IMETHODIMP
nsHTMLDNSPrefetch::nsDeferrals::Observe(nsISupports *subject,
const char *topic,
const char16_t *data)
{
if (!strcmp(topic, "xpcom-shutdown"))
Flush();
return NS_OK;
}