Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "ServiceWorkerUpdateJob.h"
8
9
#include "nsIScriptError.h"
10
#include "nsIURL.h"
11
#include "nsNetUtil.h"
12
#include "nsProxyRelease.h"
13
#include "ServiceWorkerManager.h"
14
#include "ServiceWorkerPrivate.h"
15
#include "ServiceWorkerRegistrationInfo.h"
16
#include "ServiceWorkerScriptCache.h"
17
#include "mozilla/dom/WorkerCommon.h"
18
19
namespace mozilla {
20
namespace dom {
21
22
using serviceWorkerScriptCache::OnFailure;
23
24
namespace {
25
26
/**
27
* The spec mandates slightly different behaviors for computing the scope
28
* prefix string in case a Service-Worker-Allowed header is specified versus
29
* when it's not available.
30
*
31
* With the header:
32
* "Set maxScopeString to "/" concatenated with the strings in maxScope's
33
* path (including empty strings), separated from each other by "/"."
34
* Without the header:
35
* "Set maxScopeString to "/" concatenated with the strings, except the last
36
* string that denotes the script's file name, in registration's registering
37
* script url's path (including empty strings), separated from each other by
38
* "/"."
39
*
40
* In simpler terms, if the header is not present, we should only use the
41
* "directory" part of the pathname, and otherwise the entire pathname should be
42
* used. ScopeStringPrefixMode allows the caller to specify the desired
43
* behavior.
44
*/
45
enum ScopeStringPrefixMode { eUseDirectory, eUsePath };
46
47
nsresult GetRequiredScopeStringPrefix(nsIURI* aScriptURI, nsACString& aPrefix,
48
ScopeStringPrefixMode aPrefixMode) {
49
nsresult rv;
50
if (aPrefixMode == eUseDirectory) {
51
nsCOMPtr<nsIURL> scriptURL(do_QueryInterface(aScriptURI));
52
if (NS_WARN_IF(!scriptURL)) {
53
return NS_ERROR_FAILURE;
54
}
55
56
rv = scriptURL->GetDirectory(aPrefix);
57
if (NS_WARN_IF(NS_FAILED(rv))) {
58
return rv;
59
}
60
} else if (aPrefixMode == eUsePath) {
61
rv = aScriptURI->GetPathQueryRef(aPrefix);
62
if (NS_WARN_IF(NS_FAILED(rv))) {
63
return rv;
64
}
65
} else {
66
MOZ_ASSERT_UNREACHABLE("Invalid value for aPrefixMode");
67
}
68
return NS_OK;
69
}
70
71
} // anonymous namespace
72
73
class ServiceWorkerUpdateJob::CompareCallback final
74
: public serviceWorkerScriptCache::CompareCallback {
75
RefPtr<ServiceWorkerUpdateJob> mJob;
76
77
~CompareCallback() {}
78
79
public:
80
explicit CompareCallback(ServiceWorkerUpdateJob* aJob) : mJob(aJob) {
81
MOZ_ASSERT(mJob);
82
}
83
84
virtual void ComparisonResult(nsresult aStatus, bool aInCacheAndEqual,
85
OnFailure aOnFailure,
86
const nsAString& aNewCacheName,
87
const nsACString& aMaxScope,
88
nsLoadFlags aLoadFlags) override {
89
mJob->ComparisonResult(aStatus, aInCacheAndEqual, aOnFailure, aNewCacheName,
90
aMaxScope, aLoadFlags);
91
}
92
93
NS_INLINE_DECL_REFCOUNTING(ServiceWorkerUpdateJob::CompareCallback, override)
94
};
95
96
class ServiceWorkerUpdateJob::ContinueUpdateRunnable final
97
: public LifeCycleEventCallback {
98
nsMainThreadPtrHandle<ServiceWorkerUpdateJob> mJob;
99
bool mSuccess;
100
101
public:
102
explicit ContinueUpdateRunnable(
103
const nsMainThreadPtrHandle<ServiceWorkerUpdateJob>& aJob)
104
: mJob(aJob), mSuccess(false) {
105
MOZ_ASSERT(NS_IsMainThread());
106
}
107
108
void SetResult(bool aResult) override { mSuccess = aResult; }
109
110
NS_IMETHOD
111
Run() override {
112
MOZ_ASSERT(NS_IsMainThread());
113
mJob->ContinueUpdateAfterScriptEval(mSuccess);
114
mJob = nullptr;
115
return NS_OK;
116
}
117
};
118
119
class ServiceWorkerUpdateJob::ContinueInstallRunnable final
120
: public LifeCycleEventCallback {
121
nsMainThreadPtrHandle<ServiceWorkerUpdateJob> mJob;
122
bool mSuccess;
123
124
public:
125
explicit ContinueInstallRunnable(
126
const nsMainThreadPtrHandle<ServiceWorkerUpdateJob>& aJob)
127
: mJob(aJob), mSuccess(false) {
128
MOZ_ASSERT(NS_IsMainThread());
129
}
130
131
void SetResult(bool aResult) override { mSuccess = aResult; }
132
133
NS_IMETHOD
134
Run() override {
135
MOZ_ASSERT(NS_IsMainThread());
136
mJob->ContinueAfterInstallEvent(mSuccess);
137
mJob = nullptr;
138
return NS_OK;
139
}
140
};
141
142
ServiceWorkerUpdateJob::ServiceWorkerUpdateJob(
143
nsIPrincipal* aPrincipal, const nsACString& aScope,
144
const nsACString& aScriptSpec, ServiceWorkerUpdateViaCache aUpdateViaCache)
145
: ServiceWorkerJob(Type::Update, aPrincipal, aScope, aScriptSpec),
146
mUpdateViaCache(aUpdateViaCache),
147
mOnFailure(OnFailure::DoNothing) {}
148
149
already_AddRefed<ServiceWorkerRegistrationInfo>
150
ServiceWorkerUpdateJob::GetRegistration() const {
151
MOZ_ASSERT(NS_IsMainThread());
152
RefPtr<ServiceWorkerRegistrationInfo> ref = mRegistration;
153
return ref.forget();
154
}
155
156
ServiceWorkerUpdateJob::ServiceWorkerUpdateJob(
157
Type aType, nsIPrincipal* aPrincipal, const nsACString& aScope,
158
const nsACString& aScriptSpec, ServiceWorkerUpdateViaCache aUpdateViaCache)
159
: ServiceWorkerJob(aType, aPrincipal, aScope, aScriptSpec),
160
mUpdateViaCache(aUpdateViaCache),
161
mOnFailure(serviceWorkerScriptCache::OnFailure::DoNothing) {}
162
163
ServiceWorkerUpdateJob::~ServiceWorkerUpdateJob() {}
164
165
void ServiceWorkerUpdateJob::FailUpdateJob(ErrorResult& aRv) {
166
MOZ_ASSERT(NS_IsMainThread());
167
MOZ_ASSERT(aRv.Failed());
168
169
// Cleanup after a failed installation. This essentially implements
170
// step 13 of the Install algorithm.
171
//
173
//
174
// The spec currently only runs this after an install event fails,
175
// but we must handle many more internal errors. So we check for
176
// cleanup on every non-successful exit.
177
if (mRegistration) {
178
// Some kinds of failures indicate there is something broken in the
179
// currently installed registration. In these cases we want to fully
180
// unregister.
181
if (mOnFailure == OnFailure::Uninstall) {
182
mRegistration->ClearAsCorrupt();
183
}
184
185
// Otherwise just clear the workers we may have created as part of the
186
// update process.
187
else {
188
mRegistration->ClearEvaluating();
189
mRegistration->ClearInstalling();
190
}
191
192
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
193
if (swm) {
194
swm->MaybeRemoveRegistration(mRegistration);
195
196
// Also clear the registration on disk if we are forcing uninstall
197
// due to a particularly bad failure.
198
if (mOnFailure == OnFailure::Uninstall) {
199
swm->MaybeSendUnregister(mRegistration->Principal(),
200
mRegistration->Scope());
201
}
202
}
203
}
204
205
mRegistration = nullptr;
206
207
Finish(aRv);
208
}
209
210
void ServiceWorkerUpdateJob::FailUpdateJob(nsresult aRv) {
211
ErrorResult rv(aRv);
212
FailUpdateJob(rv);
213
}
214
215
void ServiceWorkerUpdateJob::AsyncExecute() {
216
MOZ_ASSERT(NS_IsMainThread());
217
MOZ_ASSERT(GetType() == Type::Update);
218
219
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
220
if (Canceled() || !swm) {
221
FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
222
return;
223
}
224
225
// Begin step 1 of the Update algorithm.
226
//
228
229
RefPtr<ServiceWorkerRegistrationInfo> registration =
230
swm->GetRegistration(mPrincipal, mScope);
231
232
if (!registration) {
233
ErrorResult rv;
234
rv.ThrowTypeError<MSG_SW_UPDATE_BAD_REGISTRATION>(
235
NS_ConvertUTF8toUTF16(mScope), NS_LITERAL_STRING("uninstalled"));
236
FailUpdateJob(rv);
237
return;
238
}
239
240
// If a Register job with a new script executed ahead of us in the job queue,
241
// then our update for the old script no longer makes sense. Simply abort
242
// in this case.
243
RefPtr<ServiceWorkerInfo> newest = registration->Newest();
244
if (newest && !mScriptSpec.Equals(newest->ScriptSpec())) {
245
ErrorResult rv;
246
rv.ThrowTypeError<MSG_SW_UPDATE_BAD_REGISTRATION>(
247
NS_ConvertUTF8toUTF16(mScope), NS_LITERAL_STRING("changed"));
248
FailUpdateJob(rv);
249
return;
250
}
251
252
SetRegistration(registration);
253
Update();
254
}
255
256
void ServiceWorkerUpdateJob::SetRegistration(
257
ServiceWorkerRegistrationInfo* aRegistration) {
258
MOZ_ASSERT(NS_IsMainThread());
259
260
MOZ_ASSERT(!mRegistration);
261
MOZ_ASSERT(aRegistration);
262
mRegistration = aRegistration;
263
}
264
265
void ServiceWorkerUpdateJob::Update() {
266
MOZ_ASSERT(NS_IsMainThread());
267
MOZ_ASSERT(!Canceled());
268
269
// SetRegistration() must be called before Update().
270
MOZ_ASSERT(mRegistration);
271
MOZ_ASSERT(!mRegistration->GetInstalling());
272
273
// Begin the script download and comparison steps starting at step 5
274
// of the Update algorithm.
275
276
RefPtr<ServiceWorkerInfo> workerInfo = mRegistration->Newest();
277
nsAutoString cacheName;
278
279
// If the script has not changed, we need to perform a byte-for-byte
280
// comparison.
281
if (workerInfo && workerInfo->ScriptSpec().Equals(mScriptSpec)) {
282
cacheName = workerInfo->CacheName();
283
}
284
285
RefPtr<CompareCallback> callback = new CompareCallback(this);
286
287
nsresult rv = serviceWorkerScriptCache::Compare(
288
mRegistration, mPrincipal, cacheName, NS_ConvertUTF8toUTF16(mScriptSpec),
289
callback);
290
if (NS_WARN_IF(NS_FAILED(rv))) {
291
FailUpdateJob(rv);
292
return;
293
}
294
}
295
296
ServiceWorkerUpdateViaCache ServiceWorkerUpdateJob::GetUpdateViaCache() const {
297
return mUpdateViaCache;
298
}
299
300
void ServiceWorkerUpdateJob::ComparisonResult(nsresult aStatus,
301
bool aInCacheAndEqual,
302
OnFailure aOnFailure,
303
const nsAString& aNewCacheName,
304
const nsACString& aMaxScope,
305
nsLoadFlags aLoadFlags) {
306
MOZ_ASSERT(NS_IsMainThread());
307
308
mOnFailure = aOnFailure;
309
310
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
311
if (NS_WARN_IF(Canceled() || !swm)) {
312
FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
313
return;
314
}
315
316
// Handle failure of the download or comparison. This is part of Update
317
// step 5 as "If the algorithm asynchronously completes with null, then:".
318
if (NS_WARN_IF(NS_FAILED(aStatus))) {
319
FailUpdateJob(aStatus);
320
return;
321
}
322
323
// The spec validates the response before performing the byte-for-byte check.
324
// Here we perform the comparison in another module and then validate the
325
// script URL and scope. Make sure to do this validation before accepting
326
// an byte-for-byte match since the service-worker-allowed header might have
327
// changed since the last time it was installed.
328
329
// This is step 2 the "validate response" section of Update algorithm step 5.
330
// Step 1 is performed in the serviceWorkerScriptCache code.
331
332
nsCOMPtr<nsIURI> scriptURI;
333
nsresult rv = NS_NewURI(getter_AddRefs(scriptURI), mScriptSpec);
334
if (NS_WARN_IF(NS_FAILED(rv))) {
335
FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
336
return;
337
}
338
339
nsCOMPtr<nsIURI> maxScopeURI;
340
if (!aMaxScope.IsEmpty()) {
341
rv = NS_NewURI(getter_AddRefs(maxScopeURI), aMaxScope, nullptr, scriptURI);
342
if (NS_WARN_IF(NS_FAILED(rv))) {
343
FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
344
return;
345
}
346
}
347
348
nsAutoCString defaultAllowedPrefix;
349
rv = GetRequiredScopeStringPrefix(scriptURI, defaultAllowedPrefix,
350
eUseDirectory);
351
if (NS_WARN_IF(NS_FAILED(rv))) {
352
FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
353
return;
354
}
355
356
nsAutoCString maxPrefix(defaultAllowedPrefix);
357
if (maxScopeURI) {
358
rv = GetRequiredScopeStringPrefix(maxScopeURI, maxPrefix, eUsePath);
359
if (NS_WARN_IF(NS_FAILED(rv))) {
360
FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
361
return;
362
}
363
}
364
365
nsCOMPtr<nsIURI> scopeURI;
366
rv = NS_NewURI(getter_AddRefs(scopeURI), mRegistration->Scope(), nullptr,
367
scriptURI);
368
if (NS_WARN_IF(NS_FAILED(rv))) {
369
FailUpdateJob(NS_ERROR_FAILURE);
370
return;
371
}
372
373
nsAutoCString scopeString;
374
rv = scopeURI->GetPathQueryRef(scopeString);
375
if (NS_WARN_IF(NS_FAILED(rv))) {
376
FailUpdateJob(NS_ERROR_FAILURE);
377
return;
378
}
379
380
if (!StringBeginsWith(scopeString, maxPrefix)) {
381
nsAutoString message;
382
NS_ConvertUTF8toUTF16 reportScope(mRegistration->Scope());
383
NS_ConvertUTF8toUTF16 reportMaxPrefix(maxPrefix);
384
385
rv = nsContentUtils::FormatLocalizedString(
386
message, nsContentUtils::eDOM_PROPERTIES,
387
"ServiceWorkerScopePathMismatch", reportScope, reportMaxPrefix);
388
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to format localized string");
389
swm->ReportToAllClients(mScope, message, EmptyString(), EmptyString(), 0, 0,
390
nsIScriptError::errorFlag);
391
FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
392
return;
393
}
394
395
// The response has been validated, so now we can consider if its a
396
// byte-for-byte match. This is step 6 of the Update algorithm.
397
if (aInCacheAndEqual) {
398
Finish(NS_OK);
399
return;
400
}
401
402
Telemetry::Accumulate(Telemetry::SERVICE_WORKER_UPDATED, 1);
403
404
// Begin step 7 of the Update algorithm to evaluate the new script.
405
nsLoadFlags flags = aLoadFlags;
406
if (GetUpdateViaCache() == ServiceWorkerUpdateViaCache::None) {
407
flags |= nsIRequest::VALIDATE_ALWAYS;
408
}
409
410
RefPtr<ServiceWorkerInfo> sw = new ServiceWorkerInfo(
411
mRegistration->Principal(), mRegistration->Scope(), mRegistration->Id(),
412
mRegistration->Version(), mScriptSpec, aNewCacheName, flags);
413
414
// If the registration is corrupt enough to force an uninstall if the
415
// upgrade fails, then we want to make sure the upgrade takes effect
416
// if it succeeds. Therefore force the skip-waiting flag on to replace
417
// the broken worker after install.
418
if (aOnFailure == OnFailure::Uninstall) {
419
sw->SetSkipWaitingFlag();
420
}
421
422
mRegistration->SetEvaluating(sw);
423
424
nsMainThreadPtrHandle<ServiceWorkerUpdateJob> handle(
425
new nsMainThreadPtrHolder<ServiceWorkerUpdateJob>(
426
"ServiceWorkerUpdateJob", this));
427
RefPtr<LifeCycleEventCallback> callback = new ContinueUpdateRunnable(handle);
428
429
ServiceWorkerPrivate* workerPrivate = sw->WorkerPrivate();
430
MOZ_ASSERT(workerPrivate);
431
rv = workerPrivate->CheckScriptEvaluation(callback);
432
433
if (NS_WARN_IF(NS_FAILED(rv))) {
434
FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
435
return;
436
}
437
}
438
439
void ServiceWorkerUpdateJob::ContinueUpdateAfterScriptEval(
440
bool aScriptEvaluationResult) {
441
MOZ_ASSERT(NS_IsMainThread());
442
443
RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
444
if (Canceled() || !swm) {
445
FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
446
return;
447
}
448
449
// Step 7.5 of the Update algorithm verifying that the script evaluated
450
// successfully.
451
452
if (NS_WARN_IF(!aScriptEvaluationResult)) {
453
ErrorResult error;
454
455
NS_ConvertUTF8toUTF16 scriptSpec(mScriptSpec);
456
NS_ConvertUTF8toUTF16 scope(mRegistration->Scope());
457
error.ThrowTypeError<MSG_SW_SCRIPT_THREW>(scriptSpec, scope);
458
FailUpdateJob(error);
459
return;
460
}
461
462
Install();
463
}
464
465
void ServiceWorkerUpdateJob::Install() {
466
MOZ_ASSERT(NS_IsMainThread());
467
MOZ_DIAGNOSTIC_ASSERT(!Canceled());
468
469
MOZ_ASSERT(!mRegistration->GetInstalling());
470
471
// Begin step 2 of the Install algorithm.
472
//
474
475
mRegistration->TransitionEvaluatingToInstalling();
476
477
// Step 6 of the Install algorithm resolving the job promise.
478
InvokeResultCallbacks(NS_OK);
479
480
// Queue a task to fire an event named updatefound at all the
481
// ServiceWorkerRegistration.
482
mRegistration->FireUpdateFound();
483
484
nsMainThreadPtrHandle<ServiceWorkerUpdateJob> handle(
485
new nsMainThreadPtrHolder<ServiceWorkerUpdateJob>(
486
"ServiceWorkerUpdateJob", this));
487
RefPtr<LifeCycleEventCallback> callback = new ContinueInstallRunnable(handle);
488
489
// Send the install event to the worker thread
490
ServiceWorkerPrivate* workerPrivate =
491
mRegistration->GetInstalling()->WorkerPrivate();
492
nsresult rv =
493
workerPrivate->SendLifeCycleEvent(NS_LITERAL_STRING("install"), callback);
494
if (NS_WARN_IF(NS_FAILED(rv))) {
495
ContinueAfterInstallEvent(false /* aSuccess */);
496
}
497
}
498
499
void ServiceWorkerUpdateJob::ContinueAfterInstallEvent(
500
bool aInstallEventSuccess) {
501
if (Canceled()) {
502
return FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
503
}
504
505
// If we haven't been canceled we should have a registration. There appears
506
// to be a path where it gets cleared before we call into here. Assert
507
// to try to catch this condition, but don't crash in release.
508
MOZ_DIAGNOSTIC_ASSERT(mRegistration);
509
if (!mRegistration) {
510
return FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
511
}
512
513
// Continue executing the Install algorithm at step 12.
514
515
// "If installFailed is true"
516
if (NS_WARN_IF(!aInstallEventSuccess)) {
517
// The installing worker is cleaned up by FailUpdateJob().
518
FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
519
return;
520
}
521
522
MOZ_DIAGNOSTIC_ASSERT(mRegistration->GetInstalling());
523
mRegistration->TransitionInstallingToWaiting();
524
525
Finish(NS_OK);
526
527
// Step 20 calls for explicitly waiting for queued event tasks to fire.
528
// Instead, we simply queue a runnable to execute Activate. This ensures the
529
// events are flushed from the queue before proceeding.
530
531
// Step 22 of the Install algorithm. Activate is executed after the
532
// completion of this job. The controlling client and skipWaiting checks are
533
// performed in TryToActivate().
534
mRegistration->TryToActivateAsync();
535
}
536
537
} // namespace dom
538
} // namespace mozilla