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
|
/* -*- 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 "mozilla/StaticPrefs_dom.h"
#include "mozilla/dom/EndpointForReportChild.h"
#include "mozilla/dom/Fetch.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/ReportBody.h"
#include "mozilla/dom/ReportDeliver.h"
#include "mozilla/dom/Request.h"
#include "mozilla/dom/RequestBinding.h"
#include "mozilla/dom/Response.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "nsGlobalWindowInner.h"
#include "nsIGlobalObject.h"
#include "nsIXPConnect.h"
#include "nsNetUtil.h"
#include "nsStringStream.h"
namespace mozilla {
namespace dom {
namespace {
StaticRefPtr<ReportDeliver> gReportDeliver;
class ReportFetchHandler final : public PromiseNativeHandler {
public:
NS_DECL_ISUPPORTS
explicit ReportFetchHandler(
const nsTArray<ReportDeliver::ReportData>& aReportData)
: mReports(aReportData.Clone()) {}
void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
if (!gReportDeliver) {
return;
}
if (NS_WARN_IF(!aValue.isObject())) {
return;
}
JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
MOZ_ASSERT(obj);
{
Response* response = nullptr;
if (NS_WARN_IF(NS_FAILED(UNWRAP_OBJECT(Response, &obj, response)))) {
return;
}
if (response->Status() == 410) {
mozilla::ipc::PBackgroundChild* actorChild =
mozilla::ipc::BackgroundChild::GetOrCreateForCurrentThread();
for (const auto& report : mReports) {
mozilla::ipc::PrincipalInfo principalInfo;
nsresult rv =
PrincipalToPrincipalInfo(report.mPrincipal, &principalInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
continue;
}
actorChild->SendRemoveEndpoint(report.mGroupName, report.mEndpointURL,
principalInfo);
}
}
}
}
void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
if (gReportDeliver) {
for (auto& report : mReports) {
++report.mFailures;
gReportDeliver->AppendReportData(report);
}
}
}
private:
~ReportFetchHandler() = default;
nsTArray<ReportDeliver::ReportData> mReports;
};
NS_IMPL_ISUPPORTS0(ReportFetchHandler)
struct StringWriteFunc final : public JSONWriteFunc {
nsACString&
mBuffer; // The lifetime of the struct must be bound to the buffer
explicit StringWriteFunc(nsACString& aBuffer) : mBuffer(aBuffer) {}
void Write(const Span<const char>& aStr) override { mBuffer.Append(aStr); }
};
class ReportJSONWriter final : public JSONWriter {
public:
explicit ReportJSONWriter(nsACString& aOutput)
: JSONWriter(MakeUnique<StringWriteFunc>(aOutput)) {}
void JSONProperty(const Span<const char>& aProperty,
const Span<const char>& aJSON) {
Separator();
PropertyNameAndColon(aProperty);
mWriter->Write(aJSON);
}
};
void SendReports(nsTArray<ReportDeliver::ReportData>& aReports,
const nsCString& aEndPointUrl, nsIPrincipal* aPrincipal) {
if (NS_WARN_IF(aReports.IsEmpty())) {
return;
}
nsIXPConnect* xpc = nsContentUtils::XPConnect();
MOZ_ASSERT(xpc, "This should never be null!");
nsCOMPtr<nsIGlobalObject> globalObject;
{
AutoJSAPI jsapi;
jsapi.Init();
JSContext* cx = jsapi.cx();
JS::Rooted<JSObject*> sandbox(cx);
nsresult rv = xpc->CreateSandbox(cx, aPrincipal, sandbox.address());
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
// The JSContext is not in a realm, so CreateSandbox returned an unwrapped
// global.
MOZ_ASSERT(JS_IsGlobalObject(sandbox));
globalObject = xpc::NativeGlobal(sandbox);
}
if (NS_WARN_IF(!globalObject)) {
return;
}
// The body
nsAutoCString body;
ReportJSONWriter w(body);
w.StartArrayElement();
for (const auto& report : aReports) {
MOZ_ASSERT(report.mPrincipal == aPrincipal);
MOZ_ASSERT(report.mEndpointURL == aEndPointUrl);
w.StartObjectElement();
w.IntProperty("age",
(TimeStamp::Now() - report.mCreationTime).ToMilliseconds());
w.StringProperty("type", NS_ConvertUTF16toUTF8(report.mType));
w.StringProperty("url", NS_ConvertUTF16toUTF8(report.mURL));
w.StringProperty("user_agent", NS_ConvertUTF16toUTF8(report.mUserAgent));
w.JSONProperty(MakeStringSpan("body"),
Span<const char>(report.mReportBodyJSON.Data(),
report.mReportBodyJSON.Length()));
w.EndObject();
}
w.EndArray();
// The body as stream
nsCOMPtr<nsIInputStream> streamBody;
nsresult rv = NS_NewCStringInputStream(getter_AddRefs(streamBody), body);
// Headers
IgnoredErrorResult error;
RefPtr<InternalHeaders> internalHeaders =
new InternalHeaders(HeadersGuardEnum::Request);
internalHeaders->Set("Content-Type"_ns, "application/reports+json"_ns, error);
if (NS_WARN_IF(error.Failed())) {
return;
}
// URL and fragments
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), aEndPointUrl);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsCOMPtr<nsIURI> uriClone;
rv = NS_GetURIWithoutRef(uri, getter_AddRefs(uriClone));
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsAutoCString uriSpec;
rv = uriClone->GetSpec(uriSpec);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsAutoCString uriFragment;
rv = uri->GetRef(uriFragment);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
auto internalRequest = MakeSafeRefPtr<InternalRequest>(uriSpec, uriFragment);
internalRequest->SetMethod("POST"_ns);
internalRequest->SetBody(streamBody, body.Length());
internalRequest->SetHeaders(internalHeaders);
internalRequest->SetSkipServiceWorker();
// TODO: internalRequest->SetContentPolicyType(TYPE_REPORT);
internalRequest->SetMode(RequestMode::Cors);
internalRequest->SetCredentialsMode(RequestCredentials::Include);
RefPtr<Request> request =
new Request(globalObject, std::move(internalRequest), nullptr);
RequestOrUSVString fetchInput;
fetchInput.SetAsRequest() = request;
RefPtr<Promise> promise = FetchRequest(
globalObject, fetchInput, RequestInit(), CallerType::NonSystem, error);
if (error.Failed()) {
for (auto& report : aReports) {
++report.mFailures;
if (gReportDeliver) {
gReportDeliver->AppendReportData(report);
}
}
return;
}
RefPtr<ReportFetchHandler> handler = new ReportFetchHandler(aReports);
promise->AppendNativeHandler(handler);
}
} // namespace
/* static */
void ReportDeliver::Record(nsPIDOMWindowInner* aWindow, const nsAString& aType,
const nsAString& aGroupName, const nsAString& aURL,
ReportBody* aBody) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aWindow);
MOZ_ASSERT(aBody);
nsAutoCString reportBodyJSON;
ReportJSONWriter w(reportBodyJSON);
w.Start();
aBody->ToJSON(w);
w.End();
nsCOMPtr<nsIPrincipal> principal =
nsGlobalWindowInner::Cast(aWindow)->GetPrincipal();
if (NS_WARN_IF(!principal)) {
return;
}
mozilla::ipc::PrincipalInfo principalInfo;
nsresult rv = PrincipalToPrincipalInfo(principal, &principalInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
mozilla::ipc::PBackgroundChild* actorChild =
mozilla::ipc::BackgroundChild::GetOrCreateForCurrentThread();
PEndpointForReportChild* actor =
actorChild->SendPEndpointForReportConstructor(nsString(aGroupName),
principalInfo);
if (NS_WARN_IF(!actor)) {
return;
}
ReportData data;
data.mType = aType;
data.mGroupName = aGroupName;
data.mURL = aURL;
data.mCreationTime = TimeStamp::Now();
data.mReportBodyJSON = reportBodyJSON;
data.mPrincipal = principal;
data.mFailures = 0;
Navigator* navigator = aWindow->Navigator();
MOZ_ASSERT(navigator);
IgnoredErrorResult error;
navigator->GetUserAgent(data.mUserAgent, CallerType::NonSystem, error);
if (NS_WARN_IF(error.Failed())) {
return;
}
static_cast<EndpointForReportChild*>(actor)->Initialize(data);
}
/* static */
void ReportDeliver::Fetch(const ReportData& aReportData) {
if (!gReportDeliver) {
RefPtr<ReportDeliver> rd = new ReportDeliver();
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (NS_WARN_IF(!obs)) {
return;
}
obs->AddObserver(rd, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
gReportDeliver = rd;
}
gReportDeliver->AppendReportData(aReportData);
}
void ReportDeliver::AppendReportData(const ReportData& aReportData) {
if (aReportData.mFailures >
StaticPrefs::dom_reporting_delivering_maxFailures()) {
return;
}
if (NS_WARN_IF(!mReportQueue.AppendElement(aReportData, fallible))) {
return;
}
while (mReportQueue.Length() >
StaticPrefs::dom_reporting_delivering_maxReports()) {
mReportQueue.RemoveElementAt(0);
}
if (!mTimer) {
uint32_t timeout = StaticPrefs::dom_reporting_delivering_timeout() * 1000;
nsresult rv = NS_NewTimerWithCallback(getter_AddRefs(mTimer), this, timeout,
nsITimer::TYPE_ONE_SHOT);
Unused << NS_WARN_IF(NS_FAILED(rv));
}
}
NS_IMETHODIMP
ReportDeliver::Notify(nsITimer* aTimer) {
mTimer = nullptr;
nsTArray<ReportData> reports = std::move(mReportQueue);
// group reports by endpoint and nsIPrincipal
std::map<std::pair<nsCString, nsCOMPtr<nsIPrincipal>>, nsTArray<ReportData>>
reportsByPrincipal;
for (ReportData& report : reports) {
auto already_seen =
reportsByPrincipal.find({report.mEndpointURL, report.mPrincipal});
if (already_seen == reportsByPrincipal.end()) {
reportsByPrincipal.emplace(
std::make_pair(report.mEndpointURL, report.mPrincipal),
nsTArray<ReportData>({report}));
} else {
already_seen->second.AppendElement(report);
}
}
for (auto& iter : reportsByPrincipal) {
std::pair<nsCString, nsCOMPtr<nsIPrincipal>> key = iter.first;
nsTArray<ReportData>& value = iter.second;
nsCString url = key.first;
nsCOMPtr<nsIPrincipal> principal = key.second;
nsAutoCString u(url);
SendReports(value, url, principal);
}
return NS_OK;
}
NS_IMETHODIMP
ReportDeliver::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
MOZ_ASSERT(!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID));
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (NS_WARN_IF(!obs)) {
return NS_OK;
}
obs->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
if (mTimer) {
mTimer->Cancel();
mTimer = nullptr;
}
gReportDeliver = nullptr;
return NS_OK;
}
ReportDeliver::ReportDeliver() = default;
ReportDeliver::~ReportDeliver() = default;
NS_INTERFACE_MAP_BEGIN(ReportDeliver)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIObserver)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
NS_INTERFACE_MAP_END
NS_IMPL_ADDREF(ReportDeliver)
NS_IMPL_RELEASE(ReportDeliver)
} // namespace dom
} // namespace mozilla
|