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.

Mercurial (d96ee8115c5a)

VCS Links

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 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 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
/* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* 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 "OfflineCacheUpdateChild.h"
#include "OfflineCacheUpdateParent.h"
#include "nsXULAppAPI.h"
#include "OfflineCacheUpdateGlue.h"
#include "nsOfflineCacheUpdate.h"

#include "nsCPrefetchService.h"
#include "nsCURILoader.h"
#include "nsIApplicationCacheContainer.h"
#include "nsIApplicationCacheChannel.h"
#include "nsIApplicationCacheService.h"
#include "nsICachingChannel.h"
#include "nsIContent.h"
#include "nsIDocShell.h"
#include "nsIDocumentLoader.h"
#include "nsIDOMElement.h"
#include "nsIDOMWindow.h"
#include "nsIDOMOfflineResourceList.h"
#include "nsIDocument.h"
#include "nsIObserverService.h"
#include "nsIURL.h"
#include "nsIWebProgress.h"
#include "nsIWebNavigation.h"
#include "nsICryptoHash.h"
#include "nsIPermissionManager.h"
#include "nsIPrincipal.h"
#include "nsNetCID.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsThreadUtils.h"
#include "nsProxyRelease.h"
#include "mozilla/Logging.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "mozilla/Preferences.h"
#include "mozilla/Attributes.h"
#include "mozilla/Unused.h"
#include "nsIDiskSpaceWatcher.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeOwner.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/PermissionMessageUtils.h"
#include "nsContentUtils.h"
#include "mozilla/Unused.h"

using namespace mozilla;
using namespace mozilla::dom;

static nsOfflineCacheUpdateService *gOfflineCacheUpdateService = nullptr;
static bool sAllowOfflineCache = true;
static bool sAllowInsecureOfflineCache = true;

nsTHashtable<nsCStringHashKey> *nsOfflineCacheUpdateService::mAllowedDomains =
    nullptr;

nsTHashtable<nsCStringHashKey> *nsOfflineCacheUpdateService::AllowedDomains() {
  if (!mAllowedDomains) mAllowedDomains = new nsTHashtable<nsCStringHashKey>();

  return mAllowedDomains;
}

typedef mozilla::docshell::OfflineCacheUpdateParent OfflineCacheUpdateParent;
typedef mozilla::docshell::OfflineCacheUpdateChild OfflineCacheUpdateChild;
typedef mozilla::docshell::OfflineCacheUpdateGlue OfflineCacheUpdateGlue;

//
// To enable logging (see mozilla/Logging.h for full details):
//
//    set MOZ_LOG=nsOfflineCacheUpdate:5
//    set MOZ_LOG_FILE=offlineupdate.log
//
// this enables LogLevel::Debug level information and places all output in
// the file offlineupdate.log
//
LazyLogModule gOfflineCacheUpdateLog("nsOfflineCacheUpdate");

#undef LOG
#define LOG(args) \
  MOZ_LOG(gOfflineCacheUpdateLog, mozilla::LogLevel::Debug, args)

#undef LOG_ENABLED
#define LOG_ENABLED() \
  MOZ_LOG_TEST(gOfflineCacheUpdateLog, mozilla::LogLevel::Debug)

//-----------------------------------------------------------------------------
// nsOfflineCachePendingUpdate
//-----------------------------------------------------------------------------

class nsOfflineCachePendingUpdate final : public nsIWebProgressListener,
                                          public nsSupportsWeakReference {
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIWEBPROGRESSLISTENER

  nsOfflineCachePendingUpdate(nsOfflineCacheUpdateService *aService,
                              nsIURI *aManifestURI, nsIURI *aDocumentURI,
                              nsIPrincipal *aLoadingPrincipal,
                              nsIDOMDocument *aDocument)
      : mService(aService),
        mManifestURI(aManifestURI),
        mDocumentURI(aDocumentURI),
        mLoadingPrincipal(aLoadingPrincipal),
        mDidReleaseThis(false) {
    mDocument = do_GetWeakReference(aDocument);
  }

 private:
  ~nsOfflineCachePendingUpdate() {}

  RefPtr<nsOfflineCacheUpdateService> mService;
  nsCOMPtr<nsIURI> mManifestURI;
  nsCOMPtr<nsIURI> mDocumentURI;
  nsCOMPtr<nsIPrincipal> mLoadingPrincipal;
  nsCOMPtr<nsIWeakReference> mDocument;
  bool mDidReleaseThis;
};

NS_IMPL_ISUPPORTS(nsOfflineCachePendingUpdate, nsIWebProgressListener,
                  nsISupportsWeakReference)

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService::nsIWebProgressListener
//-----------------------------------------------------------------------------

NS_IMETHODIMP
nsOfflineCachePendingUpdate::OnProgressChange(nsIWebProgress *aProgress,
                                              nsIRequest *aRequest,
                                              int32_t curSelfProgress,
                                              int32_t maxSelfProgress,
                                              int32_t curTotalProgress,
                                              int32_t maxTotalProgress) {
  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCachePendingUpdate::OnStateChange(nsIWebProgress *aWebProgress,
                                           nsIRequest *aRequest,
                                           uint32_t progressStateFlags,
                                           nsresult aStatus) {
  if (mDidReleaseThis) {
    return NS_OK;
  }
  nsCOMPtr<nsIDOMDocument> updateDoc = do_QueryReferent(mDocument);
  if (!updateDoc) {
    // The document that scheduled this update has gone away,
    // we don't need to listen anymore.
    aWebProgress->RemoveProgressListener(this);
    MOZ_ASSERT(!mDidReleaseThis);
    mDidReleaseThis = true;
    NS_RELEASE_THIS();
    return NS_OK;
  }

  if (!(progressStateFlags & STATE_STOP)) {
    return NS_OK;
  }

  nsCOMPtr<mozIDOMWindowProxy> windowProxy;
  aWebProgress->GetDOMWindow(getter_AddRefs(windowProxy));
  if (!windowProxy) return NS_OK;

  auto *outerWindow = nsPIDOMWindowOuter::From(windowProxy);
  nsPIDOMWindowInner *innerWindow = outerWindow->GetCurrentInnerWindow();

  nsCOMPtr<nsIDocument> progressDoc = outerWindow->GetDoc();
  if (!progressDoc) return NS_OK;

  if (!SameCOMIdentity(progressDoc, updateDoc)) {
    return NS_OK;
  }

  LOG(("nsOfflineCachePendingUpdate::OnStateChange [%p, doc=%p]", this,
       progressDoc.get()));

  // Only schedule the update if the document loaded successfully
  if (NS_SUCCEEDED(aStatus)) {
    nsCOMPtr<nsIOfflineCacheUpdate> update;
    mService->Schedule(mManifestURI, mDocumentURI, mLoadingPrincipal, updateDoc,
                       innerWindow, nullptr, getter_AddRefs(update));
    if (mDidReleaseThis) {
      return NS_OK;
    }
  }

  aWebProgress->RemoveProgressListener(this);
  MOZ_ASSERT(!mDidReleaseThis);
  mDidReleaseThis = true;
  NS_RELEASE_THIS();

  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCachePendingUpdate::OnLocationChange(nsIWebProgress *aWebProgress,
                                              nsIRequest *aRequest,
                                              nsIURI *location,
                                              uint32_t aFlags) {
  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCachePendingUpdate::OnStatusChange(nsIWebProgress *aWebProgress,
                                            nsIRequest *aRequest,
                                            nsresult aStatus,
                                            const char16_t *aMessage) {
  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCachePendingUpdate::OnSecurityChange(nsIWebProgress *aWebProgress,
                                              nsIRequest *aRequest,
                                              uint32_t state) {
  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
  return NS_OK;
}

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService::nsISupports
//-----------------------------------------------------------------------------

NS_IMPL_ISUPPORTS(nsOfflineCacheUpdateService, nsIOfflineCacheUpdateService,
                  nsIObserver, nsISupportsWeakReference)

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService <public>
//-----------------------------------------------------------------------------

nsOfflineCacheUpdateService::nsOfflineCacheUpdateService()
    : mDisabled(false), mUpdateRunning(false), mLowFreeSpace(false) {
  MOZ_ASSERT(NS_IsMainThread());
  Preferences::AddBoolVarCache(&sAllowOfflineCache,
                               "browser.cache.offline.enable", true);
  Preferences::AddBoolVarCache(&sAllowInsecureOfflineCache,
                               "browser.cache.offline.insecure.enable", true);
}

nsOfflineCacheUpdateService::~nsOfflineCacheUpdateService() {
  MOZ_ASSERT(gOfflineCacheUpdateService == this);
  gOfflineCacheUpdateService = nullptr;

  delete mAllowedDomains;
  mAllowedDomains = nullptr;
}

nsresult nsOfflineCacheUpdateService::Init() {
  // Observe xpcom-shutdown event
  nsCOMPtr<nsIObserverService> observerService =
      mozilla::services::GetObserverService();
  if (!observerService) return NS_ERROR_FAILURE;

  nsresult rv =
      observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get the current status of the disk in terms of free space and observe
  // low device storage notifications.
  nsCOMPtr<nsIDiskSpaceWatcher> diskSpaceWatcherService =
      do_GetService("@mozilla.org/toolkit/disk-space-watcher;1");
  if (diskSpaceWatcherService) {
    diskSpaceWatcherService->GetIsDiskFull(&mLowFreeSpace);
  } else {
    NS_WARNING("Could not get disk status from nsIDiskSpaceWatcher");
  }

  rv = observerService->AddObserver(this, "disk-space-watcher", false);
  NS_ENSURE_SUCCESS(rv, rv);

  gOfflineCacheUpdateService = this;

  return NS_OK;
}

/* static */
already_AddRefed<nsOfflineCacheUpdateService>
nsOfflineCacheUpdateService::GetInstance() {
  if (!gOfflineCacheUpdateService) {
    auto serv = MakeRefPtr<nsOfflineCacheUpdateService>();
    if (NS_FAILED(serv->Init())) serv = nullptr;
    MOZ_ASSERT(gOfflineCacheUpdateService == serv.get());
    return serv.forget();
  }

  return do_AddRef(gOfflineCacheUpdateService);
}

/* static */
nsOfflineCacheUpdateService *nsOfflineCacheUpdateService::EnsureService() {
  if (!gOfflineCacheUpdateService) {
    // Make the service manager hold a long-lived reference to the service
    nsCOMPtr<nsIOfflineCacheUpdateService> service =
        do_GetService(NS_OFFLINECACHEUPDATESERVICE_CONTRACTID);
  }

  return gOfflineCacheUpdateService;
}

nsresult nsOfflineCacheUpdateService::ScheduleUpdate(
    nsOfflineCacheUpdate *aUpdate) {
  LOG(("nsOfflineCacheUpdateService::Schedule [%p, update=%p]", this, aUpdate));

  aUpdate->SetOwner(this);

  mUpdates.AppendElement(aUpdate);
  ProcessNextUpdate();

  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::ScheduleOnDocumentStop(
    nsIURI *aManifestURI, nsIURI *aDocumentURI, nsIPrincipal *aLoadingPrincipal,
    nsIDOMDocument *aDocument) {
  LOG(
      ("nsOfflineCacheUpdateService::ScheduleOnDocumentStop [%p, "
       "manifestURI=%p, documentURI=%p doc=%p]",
       this, aManifestURI, aDocumentURI, aDocument));

  nsCOMPtr<nsIDocument> doc = do_QueryInterface(aDocument);
  nsCOMPtr<nsIWebProgress> progress = do_QueryInterface(doc->GetContainer());
  NS_ENSURE_TRUE(progress, NS_ERROR_INVALID_ARG);

  // Proceed with cache update
  RefPtr<nsOfflineCachePendingUpdate> update = new nsOfflineCachePendingUpdate(
      this, aManifestURI, aDocumentURI, aLoadingPrincipal, aDocument);
  NS_ENSURE_TRUE(update, NS_ERROR_OUT_OF_MEMORY);

  nsresult rv = progress->AddProgressListener(
      update, nsIWebProgress::NOTIFY_STATE_DOCUMENT);
  NS_ENSURE_SUCCESS(rv, rv);

  // The update will release when it has scheduled itself.
  Unused << update.forget();

  return NS_OK;
}

nsresult nsOfflineCacheUpdateService::UpdateFinished(
    nsOfflineCacheUpdate *aUpdate) {
  LOG(("nsOfflineCacheUpdateService::UpdateFinished [%p, update=%p]", this,
       aUpdate));

  NS_ASSERTION(mUpdates.Length() > 0 && mUpdates[0] == aUpdate,
               "Unknown update completed");

  // keep this item alive until we're done notifying observers
  RefPtr<nsOfflineCacheUpdate> update = mUpdates[0];
  Unused << update;
  mUpdates.RemoveElementAt(0);
  mUpdateRunning = false;

  ProcessNextUpdate();

  return NS_OK;
}

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService <private>
//-----------------------------------------------------------------------------

nsresult nsOfflineCacheUpdateService::ProcessNextUpdate() {
  LOG(("nsOfflineCacheUpdateService::ProcessNextUpdate [%p, num=%zu]", this,
       mUpdates.Length()));

  if (mDisabled) return NS_ERROR_ABORT;

  if (mUpdateRunning) return NS_OK;

  if (mUpdates.Length() > 0) {
    mUpdateRunning = true;
    // Canceling the update before Begin() call will make the update
    // asynchronously finish with an error.
    if (mLowFreeSpace) {
      mUpdates[0]->Cancel();
    }
    return mUpdates[0]->Begin();
  }

  return NS_OK;
}

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService::nsIOfflineCacheUpdateService
//-----------------------------------------------------------------------------

NS_IMETHODIMP
nsOfflineCacheUpdateService::GetNumUpdates(uint32_t *aNumUpdates) {
  LOG(("nsOfflineCacheUpdateService::GetNumUpdates [%p]", this));

  *aNumUpdates = mUpdates.Length();
  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::GetUpdate(uint32_t aIndex,
                                       nsIOfflineCacheUpdate **aUpdate) {
  LOG(("nsOfflineCacheUpdateService::GetUpdate [%p, %d]", this, aIndex));

  if (aIndex < mUpdates.Length()) {
    NS_ADDREF(*aUpdate = mUpdates[aIndex]);
  } else {
    *aUpdate = nullptr;
  }

  return NS_OK;
}

nsresult nsOfflineCacheUpdateService::FindUpdate(
    nsIURI *aManifestURI, nsACString const &aOriginSuffix,
    nsIFile *aCustomProfileDir, nsOfflineCacheUpdate **aUpdate) {
  nsresult rv;

  nsCOMPtr<nsIApplicationCacheService> cacheService =
      do_GetService(NS_APPLICATIONCACHESERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString groupID;
  rv =
      cacheService->BuildGroupIDForSuffix(aManifestURI, aOriginSuffix, groupID);
  NS_ENSURE_SUCCESS(rv, rv);

  RefPtr<nsOfflineCacheUpdate> update;
  for (uint32_t i = 0; i < mUpdates.Length(); i++) {
    update = mUpdates[i];

    bool partial;
    rv = update->GetPartial(&partial);
    NS_ENSURE_SUCCESS(rv, rv);

    if (partial) {
      // Partial updates aren't considered
      continue;
    }

    if (update->IsForGroupID(groupID) &&
        update->IsForProfile(aCustomProfileDir)) {
      update.swap(*aUpdate);
      return NS_OK;
    }
  }

  return NS_ERROR_NOT_AVAILABLE;
}

nsresult nsOfflineCacheUpdateService::Schedule(
    nsIURI *aManifestURI, nsIURI *aDocumentURI, nsIPrincipal *aLoadingPrincipal,
    nsIDOMDocument *aDocument, nsPIDOMWindowInner *aWindow,
    nsIFile *aCustomProfileDir, nsIOfflineCacheUpdate **aUpdate) {
  nsCOMPtr<nsIOfflineCacheUpdate> update;
  if (GeckoProcessType_Default != XRE_GetProcessType()) {
    update = new OfflineCacheUpdateChild(aWindow);
  } else {
    update = new OfflineCacheUpdateGlue();
  }

  nsresult rv;

  if (aWindow) {
    // Ensure there is window.applicationCache object that is
    // responsible for association of the new applicationCache
    // with the corresponding document.  Just ignore the result.
    nsCOMPtr<nsIDOMOfflineResourceList> appCacheWindowObject =
        aWindow->GetApplicationCache();
  }

  rv = update->Init(aManifestURI, aDocumentURI, aLoadingPrincipal, aDocument,
                    aCustomProfileDir);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = update->Schedule();
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ADDREF(*aUpdate = update);

  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::ScheduleUpdate(nsIURI *aManifestURI,
                                            nsIURI *aDocumentURI,
                                            nsIPrincipal *aLoadingPrincipal,
                                            mozIDOMWindow *aWindow,
                                            nsIOfflineCacheUpdate **aUpdate) {
  return Schedule(aManifestURI, aDocumentURI, aLoadingPrincipal, nullptr,
                  nsPIDOMWindowInner::From(aWindow), nullptr, aUpdate);
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::ScheduleAppUpdate(
    nsIURI *aManifestURI, nsIURI *aDocumentURI, nsIPrincipal *aLoadingPrincipal,
    nsIFile *aProfileDir, nsIOfflineCacheUpdate **aUpdate) {
  return Schedule(aManifestURI, aDocumentURI, aLoadingPrincipal, nullptr,
                  nullptr, aProfileDir, aUpdate);
}

NS_IMETHODIMP nsOfflineCacheUpdateService::CheckForUpdate(
    nsIURI *aManifestURI, nsIPrincipal *aLoadingPrincipal,
    nsIObserver *aObserver) {
  if (GeckoProcessType_Default != XRE_GetProcessType()) {
    // Not intended to support this on child processes
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  nsCOMPtr<nsIOfflineCacheUpdate> update = new OfflineCacheUpdateGlue();

  nsresult rv;

  rv = update->InitForUpdateCheck(aManifestURI, aLoadingPrincipal, aObserver);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = update->Schedule();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService::nsIObserver
//-----------------------------------------------------------------------------

NS_IMETHODIMP
nsOfflineCacheUpdateService::Observe(nsISupports *aSubject, const char *aTopic,
                                     const char16_t *aData) {
  if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
    if (mUpdates.Length() > 0) mUpdates[0]->Cancel();
    mDisabled = true;
  }

  if (!strcmp(aTopic, "disk-space-watcher")) {
    if (NS_LITERAL_STRING("full").Equals(aData)) {
      mLowFreeSpace = true;
      for (uint32_t i = 0; i < mUpdates.Length(); i++) {
        mUpdates[i]->Cancel();
      }
    } else if (NS_LITERAL_STRING("free").Equals(aData)) {
      mLowFreeSpace = false;
    }
  }

  return NS_OK;
}

//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateService::nsIOfflineCacheUpdateService
//-----------------------------------------------------------------------------

static nsresult OfflineAppPermForPrincipal(nsIPrincipal *aPrincipal,
                                           nsIPrefBranch *aPrefBranch,
                                           bool pinned, bool *aAllowed) {
  *aAllowed = false;

  if (!sAllowOfflineCache) {
    return NS_OK;
  }

  if (!aPrincipal) return NS_ERROR_INVALID_ARG;

  nsCOMPtr<nsIURI> uri;
  aPrincipal->GetURI(getter_AddRefs(uri));

  if (!uri) return NS_OK;

  nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(uri);
  if (!innerURI) return NS_OK;

  // only http and https applications can use offline APIs.
  bool match;
  nsresult rv = innerURI->SchemeIs("http", &match);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!match) {
    rv = innerURI->SchemeIs("https", &match);
    NS_ENSURE_SUCCESS(rv, rv);
    if (!match) {
      return NS_OK;
    }
  } else {
    if (!sAllowInsecureOfflineCache) {
      return NS_OK;
    }
  }

  nsAutoCString domain;
  rv = innerURI->GetAsciiHost(domain);
  NS_ENSURE_SUCCESS(rv, rv);

  if (nsOfflineCacheUpdateService::AllowedDomains()->Contains(domain)) {
    *aAllowed = true;
    return NS_OK;
  }

  nsCOMPtr<nsIPermissionManager> permissionManager =
      services::GetPermissionManager();
  if (!permissionManager) {
    return NS_OK;
  }

  uint32_t perm;
  const char *permName = pinned ? "pin-app" : "offline-app";
  permissionManager->TestExactPermissionFromPrincipal(aPrincipal, permName,
                                                      &perm);

  if (perm == nsIPermissionManager::ALLOW_ACTION ||
      perm == nsIOfflineCacheUpdateService::ALLOW_NO_WARN) {
    *aAllowed = true;
  }

  // offline-apps.allow_by_default is now effective at the cache selection
  // algorithm code (nsContentSink).

  return NS_OK;
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::OfflineAppAllowed(nsIPrincipal *aPrincipal,
                                               nsIPrefBranch *aPrefBranch,
                                               bool *aAllowed) {
  return OfflineAppPermForPrincipal(aPrincipal, aPrefBranch, false, aAllowed);
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::OfflineAppAllowedForURI(nsIURI *aURI,
                                                     nsIPrefBranch *aPrefBranch,
                                                     bool *aAllowed) {
  OriginAttributes attrs;
  nsCOMPtr<nsIPrincipal> principal =
      BasePrincipal::CreateCodebasePrincipal(aURI, attrs);
  return OfflineAppPermForPrincipal(principal, aPrefBranch, false, aAllowed);
}

nsresult nsOfflineCacheUpdateService::OfflineAppPinnedForURI(
    nsIURI *aDocumentURI, nsIPrefBranch *aPrefBranch, bool *aPinned) {
  OriginAttributes attrs;
  nsCOMPtr<nsIPrincipal> principal =
      BasePrincipal::CreateCodebasePrincipal(aDocumentURI, attrs);
  return OfflineAppPermForPrincipal(principal, aPrefBranch, true, aPinned);
}

NS_IMETHODIMP
nsOfflineCacheUpdateService::AllowOfflineApp(nsIPrincipal *aPrincipal) {
  nsresult rv;

  if (!sAllowOfflineCache) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  if (!sAllowInsecureOfflineCache) {
    nsCOMPtr<nsIURI> uri;
    aPrincipal->GetURI(getter_AddRefs(uri));

    if (!uri) {
      return NS_ERROR_NOT_AVAILABLE;
    }

    nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(uri);
    if (!innerURI) {
      return NS_ERROR_NOT_AVAILABLE;
    }

    // if http then we should prevent this cache
    bool match;
    rv = innerURI->SchemeIs("http", &match);
    NS_ENSURE_SUCCESS(rv, rv);

    if (match) {
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  if (GeckoProcessType_Default != XRE_GetProcessType()) {
    ContentChild *child = ContentChild::GetSingleton();

    if (!child->SendSetOfflinePermission(IPC::Principal(aPrincipal))) {
      return NS_ERROR_FAILURE;
    }

    nsAutoCString domain;
    rv = aPrincipal->GetBaseDomain(domain);
    NS_ENSURE_SUCCESS(rv, rv);

    nsOfflineCacheUpdateService::AllowedDomains()->PutEntry(domain);
  } else {
    nsCOMPtr<nsIPermissionManager> permissionManager =
        services::GetPermissionManager();
    if (!permissionManager) return NS_ERROR_NOT_AVAILABLE;

    rv = permissionManager->AddFromPrincipal(
        aPrincipal, "offline-app", nsIPermissionManager::ALLOW_ACTION,
        nsIPermissionManager::EXPIRE_NEVER, 0);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}