summaryrefslogtreecommitdiffstats
path: root/docshell/base/BaseHistory.cpp
blob: a38fb716575954436534772c737226eb0b98178b (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
/* -*- 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 "BaseHistory.h"
#include "nsThreadUtils.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Link.h"
#include "mozilla/dom/Element.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_layout.h"

namespace mozilla {

using mozilla::dom::ContentParent;
using mozilla::dom::Link;

BaseHistory::BaseHistory() : mTrackedURIs(kTrackedUrisInitialSize) {}

BaseHistory::~BaseHistory() = default;

static constexpr nsLiteralCString kDisallowedSchemes[] = {
    "about"_ns,         "blob"_ns,       "data"_ns,     "chrome"_ns,
    "imap"_ns,          "javascript"_ns, "mailbox"_ns,  "moz-anno"_ns,
    "news"_ns,          "page-icon"_ns,  "resource"_ns, "view-source"_ns,
    "moz-extension"_ns,
};

bool BaseHistory::CanStore(nsIURI* aURI) {
  nsAutoCString scheme;
  if (NS_WARN_IF(NS_FAILED(aURI->GetScheme(scheme)))) {
    return false;
  }

  if (!scheme.EqualsLiteral("http") && !scheme.EqualsLiteral("https")) {
    for (const nsLiteralCString& disallowed : kDisallowedSchemes) {
      if (scheme.Equals(disallowed)) {
        return false;
      }
    }
  }

  nsAutoCString spec;
  aURI->GetSpec(spec);
  return spec.Length() <= StaticPrefs::browser_history_maxUrlLength();
}

void BaseHistory::ScheduleVisitedQuery(nsIURI* aURI,
                                       dom::ContentParent* aForProcess) {
  mPendingQueries.WithEntryHandle(aURI, [&](auto&& entry) {
    auto& set = entry.OrInsertWith([] { return ContentParentSet(); });
    if (aForProcess) {
      set.Insert(aForProcess);
    }
  });
  if (mStartPendingVisitedQueriesScheduled) {
    return;
  }
  mStartPendingVisitedQueriesScheduled =
      NS_SUCCEEDED(NS_DispatchToMainThreadQueue(
          NS_NewRunnableFunction(
              "BaseHistory::StartPendingVisitedQueries",
              [self = RefPtr<BaseHistory>(this)] {
                self->mStartPendingVisitedQueriesScheduled = false;
                auto queries = std::move(self->mPendingQueries);
                self->StartPendingVisitedQueries(std::move(queries));
                MOZ_DIAGNOSTIC_ASSERT(self->mPendingQueries.IsEmpty());
              }),
          EventQueuePriority::Idle));
}

void BaseHistory::CancelVisitedQueryIfPossible(nsIURI* aURI) {
  mPendingQueries.Remove(aURI);
  // TODO(bug 1591393): It could be worth to make this virtual and allow places
  // to stop the existing database query? Needs some measurement.
}

void BaseHistory::RegisterVisitedCallback(nsIURI* aURI, Link* aLink) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aURI, "Must pass a non-null URI!");
  MOZ_ASSERT(aLink, "Must pass a non-null Link!");

  if (!CanStore(aURI)) {
    aLink->VisitedQueryFinished(/* visited = */ false);
    return;
  }

  // Obtain our array of observers for this URI.
  auto* const links =
      mTrackedURIs.WithEntryHandle(aURI, [&](auto&& entry) -> ObservingLinks* {
        MOZ_DIAGNOSTIC_ASSERT(!entry || !entry->mLinks.IsEmpty(),
                              "An empty key was kept around in our hashtable!");
        if (!entry) {
          ScheduleVisitedQuery(aURI, nullptr);
        }

        return &entry.OrInsertWith([] { return ObservingLinks{}; });
      });

  if (!links) {
    return;
  }

  // Sanity check that Links are not registered more than once for a given URI.
  // This will not catch a case where it is registered for two different URIs.
  MOZ_DIAGNOSTIC_ASSERT(!links->mLinks.Contains(aLink),
                        "Already tracking this Link object!");

  links->mLinks.AppendElement(aLink);

  // If this link has already been queried and we should notify, do so now.
  switch (links->mStatus) {
    case VisitedStatus::Unknown:
      break;
    case VisitedStatus::Unvisited:
      [[fallthrough]];
    case VisitedStatus::Visited:
      aLink->VisitedQueryFinished(links->mStatus == VisitedStatus::Visited);
      break;
  }
}

void BaseHistory::UnregisterVisitedCallback(nsIURI* aURI, Link* aLink) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aURI, "Must pass a non-null URI!");
  MOZ_ASSERT(aLink, "Must pass a non-null Link object!");

  // Get the array, and remove the item from it.
  auto entry = mTrackedURIs.Lookup(aURI);
  if (!entry) {
    MOZ_ASSERT(!CanStore(aURI),
               "Trying to unregister URI that wasn't registered, "
               "and that could be visited!");
    return;
  }

  ObserverArray& observers = entry->mLinks;
  if (!observers.RemoveElement(aLink)) {
    MOZ_ASSERT_UNREACHABLE("Trying to unregister node that wasn't registered!");
    return;
  }

  // If the array is now empty, we should remove it from the hashtable.
  if (observers.IsEmpty()) {
    entry.Remove();
    CancelVisitedQueryIfPossible(aURI);
  }
}

void BaseHistory::NotifyVisited(
    nsIURI* aURI, VisitedStatus aStatus,
    const ContentParentSet* aListOfProcessesToNotify) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aStatus != VisitedStatus::Unknown);

  NotifyVisitedInThisProcess(aURI, aStatus);
  if (XRE_IsParentProcess()) {
    NotifyVisitedFromParent(aURI, aStatus, aListOfProcessesToNotify);
  }
}

void BaseHistory::NotifyVisitedInThisProcess(nsIURI* aURI,
                                             VisitedStatus aStatus) {
  if (NS_WARN_IF(!aURI)) {
    return;
  }

  auto entry = mTrackedURIs.Lookup(aURI);
  if (!entry) {
    // If we have no observers for this URI, we have nothing to notify about.
    return;
  }

  ObservingLinks& links = entry.Data();
  links.mStatus = aStatus;

  // If we have a key, it should have at least one observer.
  MOZ_ASSERT(!links.mLinks.IsEmpty());

  // Dispatch an event to each document which has a Link observing this URL.
  // These will fire asynchronously in the correct DocGroup.

  const bool visited = aStatus == VisitedStatus::Visited;
  for (Link* link : links.mLinks.BackwardRange()) {
    link->VisitedQueryFinished(visited);
  }
}

void BaseHistory::SendPendingVisitedResultsToChildProcesses() {
  MOZ_ASSERT(!mPendingResults.IsEmpty());

  mStartPendingResultsScheduled = false;

  auto results = std::move(mPendingResults);
  MOZ_ASSERT(mPendingResults.IsEmpty());

  nsTArray<ContentParent*> cplist;
  nsTArray<dom::VisitedQueryResult> resultsForProcess;
  ContentParent::GetAll(cplist);
  for (ContentParent* cp : cplist) {
    resultsForProcess.ClearAndRetainStorage();
    for (auto& result : results) {
      if (result.mProcessesToNotify.IsEmpty() ||
          result.mProcessesToNotify.Contains(cp)) {
        resultsForProcess.AppendElement(result.mResult);
      }
    }
    if (!resultsForProcess.IsEmpty()) {
      Unused << NS_WARN_IF(!cp->SendNotifyVisited(resultsForProcess));
    }
  }
}

void BaseHistory::NotifyVisitedFromParent(
    nsIURI* aURI, VisitedStatus aStatus,
    const ContentParentSet* aListOfProcessesToNotify) {
  MOZ_ASSERT(XRE_IsParentProcess());

  if (aListOfProcessesToNotify && aListOfProcessesToNotify->IsEmpty()) {
    return;
  }

  auto& result = *mPendingResults.AppendElement();
  result.mResult.visited() = aStatus == VisitedStatus::Visited;
  result.mResult.uri() = aURI;
  if (aListOfProcessesToNotify) {
    for (auto* entry : *aListOfProcessesToNotify) {
      result.mProcessesToNotify.Insert(entry);
    }
  }

  if (mStartPendingResultsScheduled) {
    return;
  }

  mStartPendingResultsScheduled = NS_SUCCEEDED(NS_DispatchToMainThreadQueue(
      NewRunnableMethod(
          "BaseHistory::SendPendingVisitedResultsToChildProcesses", this,
          &BaseHistory::SendPendingVisitedResultsToChildProcesses),
      EventQueuePriority::Idle));
}

}  // namespace mozilla