summaryrefslogtreecommitdiffstats
path: root/dom/html/HTMLDNSPrefetch.cpp
blob: 779ed23a15608155954e0996f3d19fe4420311f6 (plain)
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/* -*- 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 "HTMLDNSPrefetch.h"

#include "base/basictypes.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/HTMLLinkElement.h"
#include "mozilla/dom/HTMLAnchorElement.h"
#include "mozilla/net/NeckoCommon.h"
#include "mozilla/net/NeckoChild.h"
#include "mozilla/OriginAttributes.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "nsURLHelper.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 "nsIDNSRecord.h"
#include "nsIDNSService.h"
#include "nsICancelable.h"
#include "nsGkAtoms.h"
#include "mozilla/dom/Document.h"
#include "nsThreadUtils.h"
#include "nsITimer.h"
#include "nsIObserverService.h"

#include "mozilla/Components.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_network.h"

using namespace mozilla::net;

namespace mozilla::dom {

class NoOpDNSListener final : public nsIDNSListener {
  // This class exists to give a safe callback no-op DNSListener
 public:
  NS_DECL_THREADSAFE_ISUPPORTS
  NS_DECL_NSIDNSLISTENER

  NoOpDNSListener() = default;

 private:
  ~NoOpDNSListener() = default;
};

NS_IMPL_ISUPPORTS(NoOpDNSListener, nsIDNSListener)

NS_IMETHODIMP
NoOpDNSListener::OnLookupComplete(nsICancelable* request, nsIDNSRecord* rec,
                                  nsresult status) {
  return NS_OK;
}

// This is just a (size) optimization and could be avoided by storing the
// SupportsDNSPrefetch pointer of the element in the prefetch queue, but given
// we need this for GetURIForDNSPrefetch...
static SupportsDNSPrefetch& ToSupportsDNSPrefetch(Element& aElement) {
  if (auto* link = HTMLLinkElement::FromNode(aElement)) {
    return *link;
  }
  auto* anchor = HTMLAnchorElement::FromNode(aElement);
  MOZ_DIAGNOSTIC_ASSERT(anchor);
  return *anchor;
}

nsIURI* SupportsDNSPrefetch::GetURIForDNSPrefetch(Element& aElement) {
  MOZ_ASSERT(&ToSupportsDNSPrefetch(aElement) == this);
  if (auto* link = HTMLLinkElement::FromNode(aElement)) {
    return link->GetURI();
  }
  auto* anchor = HTMLAnchorElement::FromNode(aElement);
  MOZ_DIAGNOSTIC_ASSERT(anchor);
  return anchor->GetURI();
}

class DeferredDNSPrefetches final : public nsIWebProgressListener,
                                    public nsSupportsWeakReference,
                                    public nsIObserver {
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIWEBPROGRESSLISTENER
  NS_DECL_NSIOBSERVER

  DeferredDNSPrefetches();

  void Activate();
  nsresult Add(nsIDNSService::DNSFlags flags, SupportsDNSPrefetch&, Element&);

  void RemoveUnboundLinks();

 private:
  ~DeferredDNSPrefetches();
  void Flush();

  void SubmitQueue();
  void SubmitQueueEntry(Element& aElement, nsIDNSService::DNSFlags aFlags);

  uint16_t mHead;
  uint16_t mTail;
  uint32_t mActiveLoaderCount;

  nsCOMPtr<nsITimer> mTimer;
  bool mTimerArmed;
  static void Tick(nsITimer* aTimer, void* aClosure);

  static const int sMaxDeferred = 512;  // keep power of 2 for masking
  static const int sMaxDeferredMask = (sMaxDeferred - 1);

  struct deferred_entry {
    nsIDNSService::DNSFlags mFlags;
    // SupportsDNSPrefetch clears this raw pointer in Destroyed().
    Element* mElement;
  } mEntries[sMaxDeferred];
};

static NS_DEFINE_CID(kDNSServiceCID, NS_DNSSERVICE_CID);
static bool sInitialized = false;
static nsIDNSService* sDNSService = nullptr;
static DeferredDNSPrefetches* sPrefetches = nullptr;
static NoOpDNSListener* sDNSListener = nullptr;

nsresult HTMLDNSPrefetch::Initialize() {
  if (sInitialized) {
    NS_WARNING("Initialize() called twice");
    return NS_OK;
  }

  sPrefetches = new DeferredDNSPrefetches();
  NS_ADDREF(sPrefetches);

  sDNSListener = new NoOpDNSListener();
  NS_ADDREF(sDNSListener);

  sPrefetches->Activate();

  if (IsNeckoChild()) NeckoChild::InitNeckoChild();

  sInitialized = true;
  return NS_OK;
}

nsresult HTMLDNSPrefetch::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;
}

static bool EnsureDNSService() {
  if (sDNSService) {
    return true;
  }

  NS_IF_RELEASE(sDNSService);
  nsresult rv;
  rv = CallGetService(kDNSServiceCID, &sDNSService);
  if (NS_FAILED(rv)) {
    return false;
  }

  return !!sDNSService;
}

bool HTMLDNSPrefetch::IsAllowed(Document* aDocument) {
  // There is no need to do prefetch on non UI scenarios such as XMLHttpRequest.
  return aDocument->IsDNSPrefetchAllowed() && aDocument->GetWindow();
}

static nsIDNSService::DNSFlags GetDNSFlagsFromElement(Element& aElement) {
  nsIChannel* channel = aElement.OwnerDoc()->GetChannel();
  if (!channel) {
    return nsIDNSService::RESOLVE_DEFAULT_FLAGS;
  }
  return nsIDNSService::GetFlagsFromTRRMode(channel->GetTRRMode());
}

nsIDNSService::DNSFlags HTMLDNSPrefetch::PriorityToDNSServiceFlags(
    Priority aPriority) {
  switch (aPriority) {
    case Priority::Low:
      return nsIDNSService::RESOLVE_PRIORITY_LOW;
    case Priority::Medium:
      return nsIDNSService::RESOLVE_PRIORITY_MEDIUM;
    case Priority::High:
      return nsIDNSService::RESOLVE_DEFAULT_FLAGS;
  }
  MOZ_ASSERT_UNREACHABLE("Unknown priority");
  return nsIDNSService::RESOLVE_DEFAULT_FLAGS;
}

nsresult HTMLDNSPrefetch::DeferPrefetch(SupportsDNSPrefetch& aSupports,
                                        Element& aElement, Priority aPriority) {
  MOZ_ASSERT(&ToSupportsDNSPrefetch(aElement) == &aSupports);
  if (!(sInitialized && sPrefetches && sDNSListener) || !EnsureDNSService()) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  return sPrefetches->Add(
      GetDNSFlagsFromElement(aElement) | PriorityToDNSServiceFlags(aPriority),
      aSupports, aElement);
}

nsresult HTMLDNSPrefetch::Prefetch(
    const nsAString& hostname, bool isHttps,
    const OriginAttributes& aPartitionedPrincipalOriginAttributes,
    nsIDNSService::DNSFlags 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(
            hostname, isHttps, aPartitionedPrincipalOriginAttributes, flags);
      }
    }
    return NS_OK;
  }

  if (!(sInitialized && sPrefetches && sDNSListener) || !EnsureDNSService())
    return NS_ERROR_NOT_AVAILABLE;

  nsCOMPtr<nsICancelable> tmpOutstanding;
  nsresult rv = sDNSService->AsyncResolveNative(
      NS_ConvertUTF16toUTF8(hostname), nsIDNSService::RESOLVE_TYPE_DEFAULT,
      flags | nsIDNSService::RESOLVE_SPECULATE, nullptr, sDNSListener, nullptr,
      aPartitionedPrincipalOriginAttributes, getter_AddRefs(tmpOutstanding));
  if (NS_FAILED(rv)) {
    return rv;
  }

  if (StaticPrefs::network_dns_upgrade_with_https_rr() ||
      StaticPrefs::network_dns_use_https_rr_as_altsvc()) {
    Unused << sDNSService->AsyncResolveNative(
        NS_ConvertUTF16toUTF8(hostname), nsIDNSService::RESOLVE_TYPE_HTTPSSVC,
        flags | nsIDNSService::RESOLVE_SPECULATE, nullptr, sDNSListener,
        nullptr, aPartitionedPrincipalOriginAttributes,
        getter_AddRefs(tmpOutstanding));
  }

  return NS_OK;
}

nsresult HTMLDNSPrefetch::Prefetch(
    const nsAString& hostname, bool isHttps,
    const OriginAttributes& aPartitionedPrincipalOriginAttributes,
    nsIRequest::TRRMode aMode, Priority aPriority) {
  return Prefetch(hostname, isHttps, aPartitionedPrincipalOriginAttributes,
                  nsIDNSService::GetFlagsFromTRRMode(aMode) |
                      PriorityToDNSServiceFlags(aPriority));
}

nsresult HTMLDNSPrefetch::CancelPrefetch(SupportsDNSPrefetch& aSupports,
                                         Element& aElement, Priority aPriority,
                                         nsresult aReason) {
  MOZ_ASSERT(&ToSupportsDNSPrefetch(aElement) == &aSupports);

  if (!(sInitialized && sPrefetches && sDNSListener) || !EnsureDNSService()) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  nsIDNSService::DNSFlags flags =
      GetDNSFlagsFromElement(aElement) | PriorityToDNSServiceFlags(aPriority);

  nsIURI* uri = aSupports.GetURIForDNSPrefetch(aElement);
  if (!uri) {
    return NS_OK;
  }

  nsAutoCString hostname;
  uri->GetAsciiHost(hostname);

  nsAutoString protocol;
  bool isHttps = uri->SchemeIs("https");

  OriginAttributes oa;
  StoragePrincipalHelper::GetOriginAttributesForNetworkState(
      aElement.OwnerDoc(), oa);

  return CancelPrefetch(NS_ConvertUTF8toUTF16(hostname), isHttps, oa, flags,
                        aReason);
}

nsresult HTMLDNSPrefetch::CancelPrefetch(
    const nsAString& hostname, bool isHttps,
    const OriginAttributes& aPartitionedPrincipalOriginAttributes,
    nsIDNSService::DNSFlags 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(
            hostname, isHttps, aPartitionedPrincipalOriginAttributes, flags,
            aReason);
      }
    }
    return NS_OK;
  }

  if (!(sInitialized && sPrefetches && sDNSListener) || !EnsureDNSService()) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  // Forward cancellation to DNS service
  nsresult rv = sDNSService->CancelAsyncResolveNative(
      NS_ConvertUTF16toUTF8(hostname), nsIDNSService::RESOLVE_TYPE_DEFAULT,
      flags | nsIDNSService::RESOLVE_SPECULATE,
      nullptr,  // AdditionalInfo
      sDNSListener, aReason, aPartitionedPrincipalOriginAttributes);

  if (StaticPrefs::network_dns_upgrade_with_https_rr() ||
      StaticPrefs::network_dns_use_https_rr_as_altsvc()) {
    Unused << sDNSService->CancelAsyncResolveNative(
        NS_ConvertUTF16toUTF8(hostname), nsIDNSService::RESOLVE_TYPE_HTTPSSVC,
        flags | nsIDNSService::RESOLVE_SPECULATE,
        nullptr,  // AdditionalInfo
        sDNSListener, aReason, aPartitionedPrincipalOriginAttributes);
  }
  return rv;
}

nsresult HTMLDNSPrefetch::CancelPrefetch(
    const nsAString& hostname, bool isHttps,
    const OriginAttributes& aPartitionedPrincipalOriginAttributes,
    nsIRequest::TRRMode aTRRMode, Priority aPriority, nsresult aReason) {
  return CancelPrefetch(hostname, isHttps,
                        aPartitionedPrincipalOriginAttributes,
                        nsIDNSService::GetFlagsFromTRRMode(aTRRMode) |
                            PriorityToDNSServiceFlags(aPriority),
                        aReason);
}

void HTMLDNSPrefetch::ElementDestroyed(Element& aElement,
                                       SupportsDNSPrefetch& aSupports) {
  MOZ_ASSERT(&ToSupportsDNSPrefetch(aElement) == &aSupports);
  MOZ_ASSERT(aSupports.IsInDNSPrefetch());
  if (sPrefetches) {
    // Clean up all the possible links at once.
    sPrefetches->RemoveUnboundLinks();
  }
}

void HTMLDNSPrefetch::SendRequest(Element& aElement,
                                  nsIDNSService::DNSFlags aFlags) {
  auto& supports = ToSupportsDNSPrefetch(aElement);

  nsIURI* uri = supports.GetURIForDNSPrefetch(aElement);
  if (!uri) {
    return;
  }

  nsAutoCString hostName;
  uri->GetAsciiHost(hostName);
  if (hostName.IsEmpty()) {
    return;
  }

  bool isLocalResource = false;
  nsresult rv = NS_URIChainHasFlags(
      uri, nsIProtocolHandler::URI_IS_LOCAL_RESOURCE, &isLocalResource);
  if (NS_FAILED(rv) || isLocalResource) {
    return;
  }

  OriginAttributes oa;
  StoragePrincipalHelper::GetOriginAttributesForNetworkState(
      aElement.OwnerDoc(), oa);

  bool isHttps = uri->SchemeIs("https");

  if (IsNeckoChild()) {
    // during shutdown gNeckoChild might be null
    if (gNeckoChild) {
      gNeckoChild->SendHTMLDNSPrefetch(NS_ConvertUTF8toUTF16(hostName), isHttps,
                                       oa, aFlags);
    }
  } else {
    nsCOMPtr<nsICancelable> tmpOutstanding;

    rv = sDNSService->AsyncResolveNative(
        hostName, nsIDNSService::RESOLVE_TYPE_DEFAULT,
        aFlags | nsIDNSService::RESOLVE_SPECULATE, nullptr, sDNSListener,
        nullptr, oa, getter_AddRefs(tmpOutstanding));
    if (NS_FAILED(rv)) {
      return;
    }

    // Fetch HTTPS RR if needed.
    if (StaticPrefs::network_dns_upgrade_with_https_rr() ||
        StaticPrefs::network_dns_use_https_rr_as_altsvc()) {
      sDNSService->AsyncResolveNative(
          hostName, nsIDNSService::RESOLVE_TYPE_HTTPSSVC,
          aFlags | nsIDNSService::RESOLVE_SPECULATE, nullptr, sDNSListener,
          nullptr, oa, getter_AddRefs(tmpOutstanding));
    }
  }

  // Tell element that deferred prefetch was requested.
  supports.DNSPrefetchRequestStarted();
}

void SupportsDNSPrefetch::TryDNSPrefetch(
    Element& aOwner, HTMLDNSPrefetch::PrefetchSource aSource) {
  MOZ_ASSERT(aOwner.IsInComposedDoc());
  if (HTMLDNSPrefetch::IsAllowed(aOwner.OwnerDoc())) {
    if (!(sInitialized && sDNSListener) || !EnsureDNSService()) {
      return;
    }

    if (aSource == HTMLDNSPrefetch::PrefetchSource::AnchorSpeculativePrefetch) {
      HTMLDNSPrefetch::DeferPrefetch(*this, aOwner,
                                     HTMLDNSPrefetch::Priority::Low);
    } else if (aSource == HTMLDNSPrefetch::PrefetchSource::LinkDnsPrefetch) {
      HTMLDNSPrefetch::SendRequest(
          aOwner, GetDNSFlagsFromElement(aOwner) |
                      HTMLDNSPrefetch::PriorityToDNSServiceFlags(
                          HTMLDNSPrefetch::Priority::High));
    } else {
      MOZ_ASSERT_UNREACHABLE("Unknown DNS prefetch type");
    }
  }
}

void SupportsDNSPrefetch::CancelDNSPrefetch(Element& aOwner) {
  // If prefetch was deferred, clear flag and move on
  if (mDNSPrefetchDeferred) {
    mDNSPrefetchDeferred = false;
    // Else if prefetch was requested, clear flag and send cancellation
  } else if (mDNSPrefetchRequested) {
    mDNSPrefetchRequested = false;
    // Possible that hostname could have changed since binding, but since this
    // covers common cases, most DNS prefetch requests will be canceled
    HTMLDNSPrefetch::CancelPrefetch(
        *this, aOwner, HTMLDNSPrefetch::Priority::Low, NS_ERROR_ABORT);
  }
}

DeferredDNSPrefetches::DeferredDNSPrefetches()
    : mHead(0), mTail(0), mActiveLoaderCount(0), mTimerArmed(false) {
  mTimer = NS_NewTimer();
}

DeferredDNSPrefetches::~DeferredDNSPrefetches() {
  if (mTimerArmed) {
    mTimerArmed = false;
    mTimer->Cancel();
  }

  Flush();
}

NS_IMPL_ISUPPORTS(DeferredDNSPrefetches, nsIWebProgressListener,
                  nsISupportsWeakReference, nsIObserver)

void DeferredDNSPrefetches::Flush() {
  for (; mHead != mTail; mTail = (mTail + 1) & sMaxDeferredMask) {
    Element* element = mEntries[mTail].mElement;
    if (element) {
      ToSupportsDNSPrefetch(*element).ClearIsInDNSPrefetch();
    }
    mEntries[mTail].mElement = nullptr;
  }
}

nsresult DeferredDNSPrefetches::Add(nsIDNSService::DNSFlags flags,
                                    SupportsDNSPrefetch& aSupports,
                                    Element& aElement) {
  // The FIFO has no lock, so it can only be accessed on main thread
  NS_ASSERTION(NS_IsMainThread(),
               "DeferredDNSPrefetches::Add must be on main thread");

  aSupports.DNSPrefetchRequestDeferred();

  if (((mHead + 1) & sMaxDeferredMask) == mTail) {
    return NS_ERROR_DNS_LOOKUP_QUEUE_FULL;
  }

  aSupports.SetIsInDNSPrefetch();
  mEntries[mHead].mFlags = flags;
  mEntries[mHead].mElement = &aElement;
  mHead = (mHead + 1) & sMaxDeferredMask;

  if (!mActiveLoaderCount && !mTimerArmed && mTimer) {
    mTimerArmed = true;
    mTimer->InitWithNamedFuncCallback(
        Tick, this, 2000, nsITimer::TYPE_ONE_SHOT,
        "HTMLDNSPrefetch::DeferredDNSPrefetches::Tick");
  }

  return NS_OK;
}

void DeferredDNSPrefetches::SubmitQueue() {
  NS_ASSERTION(NS_IsMainThread(),
               "DeferredDNSPrefetches::SubmitQueue must be on main thread");
  if (!EnsureDNSService()) {
    return;
  }

  for (; mHead != mTail; mTail = (mTail + 1) & sMaxDeferredMask) {
    Element* element = mEntries[mTail].mElement;
    if (!element) {
      continue;
    }
    SubmitQueueEntry(*element, mEntries[mTail].mFlags);
    mEntries[mTail].mElement = nullptr;
  }

  if (mTimerArmed) {
    mTimerArmed = false;
    mTimer->Cancel();
  }
}

void DeferredDNSPrefetches::SubmitQueueEntry(Element& aElement,
                                             nsIDNSService::DNSFlags aFlags) {
  auto& supports = ToSupportsDNSPrefetch(aElement);
  supports.ClearIsInDNSPrefetch();

  // Only prefetch here if request was deferred and deferral not cancelled
  if (!supports.IsDNSPrefetchRequestDeferred()) {
    return;
  }

  HTMLDNSPrefetch::SendRequest(aElement, aFlags);
}

void DeferredDNSPrefetches::Activate() {
  // Register as an observer for the document loader
  nsCOMPtr<nsIWebProgress> progress = components::DocLoader::Service();
  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);
}

void DeferredDNSPrefetches::RemoveUnboundLinks() {
  uint16_t tail = mTail;
  while (mHead != tail) {
    Element* element = mEntries[tail].mElement;
    if (element && !element->IsInComposedDoc()) {
      ToSupportsDNSPrefetch(*element).ClearIsInDNSPrefetch();
      mEntries[tail].mElement = nullptr;
    }
    tail = (tail + 1) & sMaxDeferredMask;
  }
}

// nsITimer related method

void DeferredDNSPrefetches::Tick(nsITimer* aTimer, void* aClosure) {
  auto* self = static_cast<DeferredDNSPrefetches*>(aClosure);

  NS_ASSERTION(NS_IsMainThread(),
               "DeferredDNSPrefetches::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
DeferredDNSPrefetches::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(),
               "DeferredDNSPrefetches::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
DeferredDNSPrefetches::OnProgressChange(nsIWebProgress* aProgress,
                                        nsIRequest* aRequest,
                                        int32_t curSelfProgress,
                                        int32_t maxSelfProgress,
                                        int32_t curTotalProgress,
                                        int32_t maxTotalProgress) {
  return NS_OK;
}

NS_IMETHODIMP
DeferredDNSPrefetches::OnLocationChange(nsIWebProgress* aWebProgress,
                                        nsIRequest* aRequest, nsIURI* location,
                                        uint32_t aFlags) {
  return NS_OK;
}

NS_IMETHODIMP
DeferredDNSPrefetches::OnStatusChange(nsIWebProgress* aWebProgress,
                                      nsIRequest* aRequest, nsresult aStatus,
                                      const char16_t* aMessage) {
  return NS_OK;
}

NS_IMETHODIMP
DeferredDNSPrefetches::OnSecurityChange(nsIWebProgress* aWebProgress,
                                        nsIRequest* aRequest, uint32_t aState) {
  return NS_OK;
}

NS_IMETHODIMP
DeferredDNSPrefetches::OnContentBlockingEvent(nsIWebProgress* aWebProgress,
                                              nsIRequest* aRequest,
                                              uint32_t aEvent) {
  return NS_OK;
}

//////////// nsIObserver method

NS_IMETHODIMP
DeferredDNSPrefetches::Observe(nsISupports* subject, const char* topic,
                               const char16_t* data) {
  if (!strcmp(topic, "xpcom-shutdown")) Flush();

  return NS_OK;
}

}  // namespace mozilla::dom