DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (d38398e5144e)

VCS Links

ClientFocusRunnable

ClientNavigateRunnable

ResolveOrRejectPromiseRunnable

WebProgressListener

Line Code
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
/* -*- 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 "ServiceWorkerWindowClient.h"

#include "js/Value.h"
#include "mozilla/Mutex.h"
#include "mozilla/dom/ClientBinding.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseWorkerProxy.h"
#include "mozilla/UniquePtr.h"
#include "nsContentUtils.h"
#include "nsGlobalWindow.h"
#include "nsIDocShell.h"
#include "nsIDocShellLoadInfo.h"
#include "nsIDocument.h"
#include "nsIGlobalObject.h"
#include "nsIPrincipal.h"
#include "nsIScriptSecurityManager.h"
#include "nsIWebNavigation.h"
#include "nsIWebProgress.h"
#include "nsIWebProgressListener.h"
#include "nsString.h"
#include "nsWeakReference.h"
#include "ServiceWorker.h"
#include "ServiceWorkerInfo.h"
#include "ServiceWorkerManager.h"
#include "WorkerPrivate.h"
#include "WorkerScope.h"

using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::dom::workers;

using mozilla::UniquePtr;

JSObject*
ServiceWorkerWindowClient::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
  return WindowClientBinding::Wrap(aCx, this, aGivenProto);
}

namespace {

class ResolveOrRejectPromiseRunnable final : public WorkerRunnable
{
  RefPtr<PromiseWorkerProxy> mPromiseProxy;
  UniquePtr<ServiceWorkerClientInfo> mClientInfo;
  nsresult mRv;

public:
  // Passing a null clientInfo will resolve the promise with a null value.
  ResolveOrRejectPromiseRunnable(
    WorkerPrivate* aWorkerPrivate, PromiseWorkerProxy* aPromiseProxy,
    UniquePtr<ServiceWorkerClientInfo>&& aClientInfo)
    : WorkerRunnable(aWorkerPrivate)
    , mPromiseProxy(aPromiseProxy)
    , mClientInfo(Move(aClientInfo))
    , mRv(NS_OK)
  {
    AssertIsOnMainThread();
  }

  // Reject the promise with passed nsresult.
  ResolveOrRejectPromiseRunnable(WorkerPrivate* aWorkerPrivate,
                                 PromiseWorkerProxy* aPromiseProxy,
                                 nsresult aRv)
    : WorkerRunnable(aWorkerPrivate)
    , mPromiseProxy(aPromiseProxy)
    , mClientInfo(nullptr)
    , mRv(aRv)
  {
    MOZ_ASSERT(NS_FAILED(aRv));
    AssertIsOnMainThread();
  }

  bool
  WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
  {
    MOZ_ASSERT(aWorkerPrivate);
    aWorkerPrivate->AssertIsOnWorkerThread();

    RefPtr<Promise> promise = mPromiseProxy->WorkerPromise();
    MOZ_ASSERT(promise);

    if (NS_WARN_IF(NS_FAILED(mRv))) {
      promise->MaybeReject(mRv);
    } else if (mClientInfo) {
      RefPtr<ServiceWorkerWindowClient> client =
        new ServiceWorkerWindowClient(promise->GetParentObject(), *mClientInfo);
      promise->MaybeResolve(client);
    } else {
      promise->MaybeResolve(JS::NullHandleValue);
    }

    // Release the reference on the worker thread.
    mPromiseProxy->CleanUp();

    return true;
  }
};

class ClientFocusRunnable final : public Runnable
{
  uint64_t mWindowId;
  RefPtr<PromiseWorkerProxy> mPromiseProxy;

public:
  ClientFocusRunnable(uint64_t aWindowId, PromiseWorkerProxy* aPromiseProxy)
    : mWindowId(aWindowId)
    , mPromiseProxy(aPromiseProxy)
  {
    MOZ_ASSERT(mPromiseProxy);
  }

  NS_IMETHOD
  Run() override
  {
    AssertIsOnMainThread();
    nsGlobalWindow* window = nsGlobalWindow::GetInnerWindowWithId(mWindowId);
    UniquePtr<ServiceWorkerClientInfo> clientInfo;

    if (window) {
      nsCOMPtr<nsIDocument> doc = window->GetDocument();
      if (doc) {
        nsContentUtils::DispatchFocusChromeEvent(window->GetOuterWindow());
        clientInfo.reset(new ServiceWorkerClientInfo(doc));
      }
    }

    DispatchResult(Move(clientInfo));
    return NS_OK;
  }

private:
  void
  DispatchResult(UniquePtr<ServiceWorkerClientInfo>&& aClientInfo)
  {
    AssertIsOnMainThread();
    MutexAutoLock lock(mPromiseProxy->Lock());
    if (mPromiseProxy->CleanedUp()) {
      return;
    }

    RefPtr<ResolveOrRejectPromiseRunnable> resolveRunnable;
    if (aClientInfo) {
      resolveRunnable = new ResolveOrRejectPromiseRunnable(
        mPromiseProxy->GetWorkerPrivate(), mPromiseProxy, Move(aClientInfo));
    } else {
      resolveRunnable = new ResolveOrRejectPromiseRunnable(
        mPromiseProxy->GetWorkerPrivate(), mPromiseProxy,
        NS_ERROR_DOM_INVALID_ACCESS_ERR);
    }

    resolveRunnable->Dispatch();
  }
};

} // namespace

already_AddRefed<Promise>
ServiceWorkerWindowClient::Focus(ErrorResult& aRv) const
{
  WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(workerPrivate);
  workerPrivate->AssertIsOnWorkerThread();

  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
  MOZ_ASSERT(global);

  RefPtr<Promise> promise = Promise::Create(global, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  if (workerPrivate->GlobalScope()->WindowInteractionAllowed()) {
    RefPtr<PromiseWorkerProxy> promiseProxy =
      PromiseWorkerProxy::Create(workerPrivate, promise);
    if (promiseProxy) {
      RefPtr<ClientFocusRunnable> r = new ClientFocusRunnable(mWindowId,
                                                              promiseProxy);
      MOZ_ALWAYS_SUCCEEDS(workerPrivate->DispatchToMainThread(r.forget()));
    } else {
      promise->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
    }

  } else {
    promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
  }

  return promise.forget();
}

class WebProgressListener final : public nsIWebProgressListener,
                                  public nsSupportsWeakReference
{
public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(WebProgressListener,
                                           nsIWebProgressListener)

  WebProgressListener(PromiseWorkerProxy* aPromiseProxy,
                      ServiceWorkerPrivate* aServiceWorkerPrivate,
                      nsPIDOMWindowOuter* aWindow, nsIURI* aBaseURI)
    : mPromiseProxy(aPromiseProxy)
    , mServiceWorkerPrivate(aServiceWorkerPrivate)
    , mWindow(aWindow)
    , mBaseURI(aBaseURI)
  {
    MOZ_ASSERT(aPromiseProxy);
    MOZ_ASSERT(aServiceWorkerPrivate);
    MOZ_ASSERT(aWindow);
    MOZ_ASSERT(aWindow->IsOuterWindow());
    MOZ_ASSERT(aBaseURI);
    AssertIsOnMainThread();

    mServiceWorkerPrivate->StoreISupports(static_cast<nsIWebProgressListener*>(this));
  }

  NS_IMETHOD
  OnStateChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
                uint32_t aStateFlags, nsresult aStatus) override
  {
    if (!(aStateFlags & STATE_IS_DOCUMENT) ||
        !(aStateFlags & (STATE_STOP | STATE_TRANSFERRING))) {
      return NS_OK;
    }

    // This is safe because our caller holds a strong ref.
    mServiceWorkerPrivate->RemoveISupports(static_cast<nsIWebProgressListener*>(this));
    aWebProgress->RemoveProgressListener(this);

    WorkerPrivate* workerPrivate;

    {
      MutexAutoLock lock(mPromiseProxy->Lock());
      if (mPromiseProxy->CleanedUp()) {
        return NS_OK;
      }

      workerPrivate = mPromiseProxy->GetWorkerPrivate();
    }

    nsCOMPtr<nsIDocument> doc = mWindow->GetExtantDoc();

    RefPtr<ResolveOrRejectPromiseRunnable> resolveRunnable;
    UniquePtr<ServiceWorkerClientInfo> clientInfo;
    if (!doc) {
      resolveRunnable = new ResolveOrRejectPromiseRunnable(
        workerPrivate, mPromiseProxy, NS_ERROR_TYPE_ERR);
      resolveRunnable->Dispatch();

      return NS_OK;
    }

    // Check same origin.
    nsCOMPtr<nsIScriptSecurityManager> securityManager =
      nsContentUtils::GetSecurityManager();
    nsresult rv = securityManager->CheckSameOriginURI(doc->GetOriginalURI(),
                                                      mBaseURI, false);

    if (NS_SUCCEEDED(rv)) {
      nsContentUtils::DispatchFocusChromeEvent(mWindow->GetOuterWindow());
      clientInfo.reset(new ServiceWorkerClientInfo(doc));
    }

    resolveRunnable = new ResolveOrRejectPromiseRunnable(
      workerPrivate, mPromiseProxy, Move(clientInfo));
    resolveRunnable->Dispatch();

    return NS_OK;
  }

  NS_IMETHOD
  OnProgressChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
                   int32_t aCurSelfProgress, int32_t aMaxSelfProgress,
                   int32_t aCurTotalProgress,
                   int32_t aMaxTotalProgress) override
  {
    MOZ_CRASH("Unexpected notification.");
    return NS_OK;
  }

  NS_IMETHOD
  OnLocationChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
                   nsIURI* aLocation, uint32_t aFlags) override
  {
    MOZ_CRASH("Unexpected notification.");
    return NS_OK;
  }

  NS_IMETHOD
  OnStatusChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
                 nsresult aStatus, const char16_t* aMessage) override
  {
    MOZ_CRASH("Unexpected notification.");
    return NS_OK;
  }

  NS_IMETHOD
  OnSecurityChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
                   uint32_t aState) override
  {
    MOZ_CRASH("Unexpected notification.");
    return NS_OK;
  }

private:
  ~WebProgressListener() {}

  RefPtr<PromiseWorkerProxy> mPromiseProxy;
  RefPtr<ServiceWorkerPrivate> mServiceWorkerPrivate;
  nsCOMPtr<nsPIDOMWindowOuter> mWindow;
  nsCOMPtr<nsIURI> mBaseURI;
};

NS_IMPL_CYCLE_COLLECTING_ADDREF(WebProgressListener)
NS_IMPL_CYCLE_COLLECTING_RELEASE(WebProgressListener)
NS_IMPL_CYCLE_COLLECTION(WebProgressListener, mPromiseProxy,
                         mServiceWorkerPrivate, mWindow)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(WebProgressListener)
  NS_INTERFACE_MAP_ENTRY(nsIWebProgressListener)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END

class ClientNavigateRunnable final : public Runnable
{
  uint64_t mWindowId;
  nsString mUrl;
  nsCString mBaseUrl;
  nsString mScope;
  RefPtr<PromiseWorkerProxy> mPromiseProxy;
  MOZ_INIT_OUTSIDE_CTOR WorkerPrivate* mWorkerPrivate;

public:
  ClientNavigateRunnable(uint64_t aWindowId, const nsAString& aUrl,
                         const nsAString& aScope,
                         PromiseWorkerProxy* aPromiseProxy)
    : mWindowId(aWindowId)
    , mUrl(aUrl)
    , mScope(aScope)
    , mPromiseProxy(aPromiseProxy)
    , mWorkerPrivate(nullptr)
  {
    MOZ_ASSERT(aPromiseProxy);
    MOZ_ASSERT(aPromiseProxy->GetWorkerPrivate());
    aPromiseProxy->GetWorkerPrivate()->AssertIsOnWorkerThread();
  }

  NS_IMETHOD
  Run() override
  {
    AssertIsOnMainThread();

    nsCOMPtr<nsIPrincipal> principal;

    {
      MutexAutoLock lock(mPromiseProxy->Lock());
      if (mPromiseProxy->CleanedUp()) {
        return NS_OK;
      }

      mWorkerPrivate = mPromiseProxy->GetWorkerPrivate();
      WorkerPrivate::LocationInfo& info = mWorkerPrivate->GetLocationInfo();
      mBaseUrl = info.mHref;
      principal = mWorkerPrivate->GetPrincipal();
      MOZ_DIAGNOSTIC_ASSERT(principal);
    }

    nsCOMPtr<nsIURI> baseUrl;
    nsCOMPtr<nsIURI> url;
    nsresult rv = ParseUrl(getter_AddRefs(baseUrl), getter_AddRefs(url));

    if (NS_WARN_IF(NS_FAILED(rv))) {
      return RejectPromise(NS_ERROR_TYPE_ERR);
    }

    rv = principal->CheckMayLoad(url, true, false);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return RejectPromise(rv);
    }

    nsGlobalWindow* window;
    rv = Navigate(url, principal, &window);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return RejectPromise(rv);
    }

    nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
    nsCOMPtr<nsIWebProgress> webProgress = do_GetInterface(docShell);
    if (NS_WARN_IF(!webProgress)) {
      return NS_ERROR_FAILURE;
    }

    RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
    if (!swm) {
      return NS_ERROR_FAILURE;
    }

    RefPtr<ServiceWorkerRegistrationInfo> registration =
      swm->GetRegistration(principal, NS_ConvertUTF16toUTF8(mScope));
    if (NS_WARN_IF(!registration)) {
      return NS_ERROR_FAILURE;
    }
    RefPtr<ServiceWorkerInfo> serviceWorkerInfo =
      registration->GetServiceWorkerInfoById(mWorkerPrivate->ServiceWorkerID());
    if (NS_WARN_IF(!serviceWorkerInfo)) {
      return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIWebProgressListener> listener =
      new WebProgressListener(mPromiseProxy, serviceWorkerInfo->WorkerPrivate(),
                              window->GetOuterWindow(), baseUrl);

    rv = webProgress->AddProgressListener(
      listener, nsIWebProgress::NOTIFY_STATE_DOCUMENT);

    if (NS_WARN_IF(NS_FAILED(rv))) {
      return RejectPromise(rv);
    }

    return NS_OK;
  }

private:
  nsresult
  RejectPromise(nsresult aRv)
  {
    MOZ_ASSERT(mWorkerPrivate);
    RefPtr<ResolveOrRejectPromiseRunnable> resolveRunnable =
      new ResolveOrRejectPromiseRunnable(mWorkerPrivate, mPromiseProxy, aRv);

    resolveRunnable->Dispatch();
    return NS_OK;
  }

  nsresult
  ResolvePromise(UniquePtr<ServiceWorkerClientInfo>&& aClientInfo)
  {
    MOZ_ASSERT(mWorkerPrivate);
    RefPtr<ResolveOrRejectPromiseRunnable> resolveRunnable =
      new ResolveOrRejectPromiseRunnable(mWorkerPrivate, mPromiseProxy,
                                         Move(aClientInfo));

    resolveRunnable->Dispatch();
    return NS_OK;
  }

  nsresult
  ParseUrl(nsIURI** aBaseUrl, nsIURI** aUrl)
  {
    MOZ_ASSERT(aBaseUrl);
    MOZ_ASSERT(aUrl);
    AssertIsOnMainThread();

    nsCOMPtr<nsIURI> baseUrl;
    nsresult rv = NS_NewURI(getter_AddRefs(baseUrl), mBaseUrl);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIURI> url;
    rv = NS_NewURI(getter_AddRefs(url), mUrl, nullptr, baseUrl);
    NS_ENSURE_SUCCESS(rv, rv);

    baseUrl.forget(aBaseUrl);
    url.forget(aUrl);

    return NS_OK;
  }

  nsresult
  Navigate(nsIURI* aUrl, nsIPrincipal* aPrincipal, nsGlobalWindow** aWindow)
  {
    MOZ_ASSERT(aWindow);

    nsGlobalWindow* window = nsGlobalWindow::GetInnerWindowWithId(mWindowId);
    if (NS_WARN_IF(!window)) {
      return NS_ERROR_TYPE_ERR;
    }

    nsCOMPtr<nsIDocument> doc = window->GetDocument();
    if (NS_WARN_IF(!doc)) {
      return NS_ERROR_TYPE_ERR;
    }

    if (NS_WARN_IF(!doc->IsActive())) {
      return NS_ERROR_TYPE_ERR;
    }

    nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
    if (NS_WARN_IF(!docShell)) {
      return NS_ERROR_TYPE_ERR;
    }

    nsCOMPtr<nsIDocShellLoadInfo> loadInfo;
    nsresult rv = docShell->CreateLoadInfo(getter_AddRefs(loadInfo));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    loadInfo->SetTriggeringPrincipal(aPrincipal);
    loadInfo->SetReferrer(doc->GetOriginalURI());
    loadInfo->SetReferrerPolicy(doc->GetReferrerPolicy());
    loadInfo->SetLoadType(nsIDocShellLoadInfo::loadStopContentAndReplace);
    loadInfo->SetSourceDocShell(docShell);
    rv =
      docShell->LoadURI(aUrl, loadInfo, nsIWebNavigation::LOAD_FLAGS_NONE, true);

    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    *aWindow = window;
    return NS_OK;
  }
};

already_AddRefed<Promise>
ServiceWorkerWindowClient::Navigate(const nsAString& aUrl, ErrorResult& aRv)
{
  WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(workerPrivate);
  workerPrivate->