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.

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 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
/* -*- 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/Assertions.h"
#include "mozilla/LinkedList.h"

#include "nsCORSListenerProxy.h"
#include "nsIChannel.h"
#include "nsIHttpChannel.h"
#include "HttpChannelChild.h"
#include "nsIHttpChannelInternal.h"
#include "nsError.h"
#include "nsContentUtils.h"
#include "nsIScriptSecurityManager.h"
#include "nsNetUtil.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsMimeTypes.h"
#include "nsIStreamConverterService.h"
#include "nsStringStream.h"
#include "nsGkAtoms.h"
#include "nsWhitespaceTokenizer.h"
#include "nsIChannelEventSink.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "nsCharSeparatedTokenizer.h"
#include "nsAsyncRedirectVerifyHelper.h"
#include "nsClassHashtable.h"
#include "nsHashKeys.h"
#include "nsStreamUtils.h"
#include "mozilla/Preferences.h"
#include "nsIScriptError.h"
#include "nsILoadGroup.h"
#include "nsILoadContext.h"
#include "nsIConsoleService.h"
#include "nsIDOMNode.h"
#include "nsIDOMWindowUtils.h"
#include "nsIDOMWindow.h"
#include "nsINetworkInterceptController.h"
#include "nsNullPrincipal.h"
#include "nsICorsPreflightCallback.h"
#include "nsISupportsImpl.h"
#include "mozilla/LoadInfo.h"
#include "nsIHttpHeaderVisitor.h"
#include <algorithm>

using namespace mozilla;

#define PREFLIGHT_CACHE_SIZE 100

static bool gDisableCORS = false;
static bool gDisableCORSPrivateData = false;

static void
LogBlockedRequest(nsIRequest* aRequest,
                  const char* aProperty,
                  const char16_t* aParam)
{
  nsresult rv = NS_OK;

  // Build the error object and log it to the console
  nsCOMPtr<nsIConsoleService> console(do_GetService(NS_CONSOLESERVICE_CONTRACTID, &rv));
  if (NS_FAILED(rv)) {
    NS_WARNING("Failed to log blocked cross-site request (no console)");
    return;
  }

  nsCOMPtr<nsIScriptError> scriptError =
    do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    NS_WARNING("Failed to log blocked cross-site request (no scriptError)");
    return;
  }

  nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
  nsCOMPtr<nsIURI> aUri;
  channel->GetURI(getter_AddRefs(aUri));
  nsAutoCString spec;
  if (aUri) {
    spec = aUri->GetSpecOrDefault();
  }

  // Generate the error message
  nsXPIDLString blockedMessage;
  NS_ConvertUTF8toUTF16 specUTF16(spec);
  const char16_t* params[] = { specUTF16.get(), aParam };
  rv = nsContentUtils::FormatLocalizedString(nsContentUtils::eSECURITY_PROPERTIES,
                                             aProperty,
                                             params,
                                             blockedMessage);

  if (NS_FAILED(rv)) {
    NS_WARNING("Failed to log blocked cross-site request (no formalizedStr");
    return;
  }

  nsAutoString msg(blockedMessage.get());

  // query innerWindowID and log to web console, otherwise log to
  // the error to the browser console.
  uint64_t innerWindowID = nsContentUtils::GetInnerWindowID(aRequest);

  if (innerWindowID > 0) {
    rv = scriptError->InitWithWindowID(msg,
                                       EmptyString(), // sourceName
                                       EmptyString(), // sourceLine
                                       0,             // lineNumber
                                       0,             // columnNumber
                                       nsIScriptError::warningFlag,
                                       "CORS",
                                       innerWindowID);
  }
  else {
    rv = scriptError->Init(msg,
                           EmptyString(), // sourceName
                           EmptyString(), // sourceLine
                           0,             // lineNumber
                           0,             // columnNumber
                           nsIScriptError::warningFlag,
                           "CORS");
  }
  if (NS_FAILED(rv)) {
    NS_WARNING("Failed to log blocked cross-site request (scriptError init failed)");
    return;
  }
  console->LogMessage(scriptError);
}

//////////////////////////////////////////////////////////////////////////
// Preflight cache

class nsPreflightCache
{
public:
  struct TokenTime
  {
    nsCString token;
    TimeStamp expirationTime;
  };

  struct CacheEntry : public LinkedListElement<CacheEntry>
  {
    explicit CacheEntry(nsCString& aKey)
      : mKey(aKey)
    {
      MOZ_COUNT_CTOR(nsPreflightCache::CacheEntry);
    }

    ~CacheEntry()
    {
      MOZ_COUNT_DTOR(nsPreflightCache::CacheEntry);
    }

    void PurgeExpired(TimeStamp now);
    bool CheckRequest(const nsCString& aMethod,
                        const nsTArray<nsCString>& aCustomHeaders);

    nsCString mKey;
    nsTArray<TokenTime> mMethods;
    nsTArray<TokenTime> mHeaders;
  };

  nsPreflightCache()
  {
    MOZ_COUNT_CTOR(nsPreflightCache);
  }

  ~nsPreflightCache()
  {
    Clear();
    MOZ_COUNT_DTOR(nsPreflightCache);
  }

  bool Initialize()
  {
    return true;
  }

  CacheEntry* GetEntry(nsIURI* aURI, nsIPrincipal* aPrincipal,
                       bool aWithCredentials, bool aCreate);
  void RemoveEntries(nsIURI* aURI, nsIPrincipal* aPrincipal);

  void Clear();

private:
  static bool GetCacheKey(nsIURI* aURI, nsIPrincipal* aPrincipal,
                            bool aWithCredentials, nsACString& _retval);

  nsClassHashtable<nsCStringHashKey, CacheEntry> mTable;
  LinkedList<CacheEntry> mList;
};

// Will be initialized in EnsurePreflightCache.
static nsPreflightCache* sPreflightCache = nullptr;

static bool EnsurePreflightCache()
{
  if (sPreflightCache)
    return true;

  nsAutoPtr<nsPreflightCache> newCache(new nsPreflightCache());

  if (newCache->Initialize()) {
    sPreflightCache = newCache.forget();
    return true;
  }

  return false;
}

void
nsPreflightCache::CacheEntry::PurgeExpired(TimeStamp now)
{
  uint32_t i;
  for (i = 0; i < mMethods.Length(); ++i) {
    if (now >= mMethods[i].expirationTime) {
      mMethods.RemoveElementAt(i--);
    }
  }
  for (i = 0; i < mHeaders.Length(); ++i) {
    if (now >= mHeaders[i].expirationTime) {
      mHeaders.RemoveElementAt(i--);
    }
  }
}

bool
nsPreflightCache::CacheEntry::CheckRequest(const nsCString& aMethod,
                                           const nsTArray<nsCString>& aHeaders)
{
  PurgeExpired(TimeStamp::NowLoRes());

  if (!aMethod.EqualsLiteral("GET") && !aMethod.EqualsLiteral("POST")) {
    uint32_t i;
    for (i = 0; i < mMethods.Length(); ++i) {
      if (aMethod.Equals(mMethods[i].token))
        break;
    }
    if (i == mMethods.Length()) {
      return false;
    }
  }

  for (uint32_t i = 0; i < aHeaders.Length(); ++i) {
    uint32_t j;
    for (j = 0; j < mHeaders.Length(); ++j) {
      if (aHeaders[i].Equals(mHeaders[j].token,
                             nsCaseInsensitiveCStringComparator())) {
        break;
      }
    }
    if (j == mHeaders.Length()) {
      return false;
    }
  }

  return true;
}

nsPreflightCache::CacheEntry*
nsPreflightCache::GetEntry(nsIURI* aURI,
                           nsIPrincipal* aPrincipal,
                           bool aWithCredentials,
                           bool aCreate)
{
  nsCString key;
  if (!GetCacheKey(aURI, aPrincipal, aWithCredentials, key)) {
    NS_WARNING("Invalid cache key!");
    return nullptr;
  }

  CacheEntry* existingEntry = nullptr;

  if (mTable.Get(key, &existingEntry)) {
    // Entry already existed so just return it. Also update the LRU list.

    // Move to the head of the list.
    existingEntry->removeFrom(mList);
    mList.insertFront(existingEntry);

    return existingEntry;
  }

  if (!aCreate) {
    return nullptr;
  }

  // This is a new entry, allocate and insert into the table now so that any
  // failures don't cause items to be removed from a full cache.
  CacheEntry* newEntry = new CacheEntry(key);
  if (!newEntry) {
    NS_WARNING("Failed to allocate new cache entry!");
    return nullptr;
  }

  NS_ASSERTION(mTable.Count() <= PREFLIGHT_CACHE_SIZE,
               "Something is borked, too many entries in the cache!");

  // Now enforce the max count.
  if (mTable.Count() == PREFLIGHT_CACHE_SIZE) {
    // Try to kick out all the expired entries.
    TimeStamp now = TimeStamp::NowLoRes();
    for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) {
      nsAutoPtr<CacheEntry>& entry = iter.Data();
      entry->PurgeExpired(now);

      if (entry->mHeaders.IsEmpty() &&
          entry->mMethods.IsEmpty()) {
        // Expired, remove from the list as well as the hash table.
        entry->removeFrom(sPreflightCache->mList);
        iter.Remove();
      }
    }

    // If that didn't remove anything then kick out the least recently used
    // entry.
    if (mTable.Count() == PREFLIGHT_CACHE_SIZE) {
      CacheEntry* lruEntry = static_cast<CacheEntry*>(mList.popLast());
      MOZ_ASSERT(lruEntry);

      // This will delete 'lruEntry'.
      mTable.Remove(lruEntry->mKey);

      NS_ASSERTION(mTable.Count() == PREFLIGHT_CACHE_SIZE - 1,
                   "Somehow tried to remove an entry that was never added!");
    }
  }

  mTable.Put(key, newEntry);
  mList.insertFront(newEntry);

  return newEntry;
}

void
nsPreflightCache::RemoveEntries(nsIURI* aURI, nsIPrincipal* aPrincipal)
{
  CacheEntry* entry;
  nsCString key;
  if (GetCacheKey(aURI, aPrincipal, true, key) &&
      mTable.Get(key, &entry)) {
    entry->removeFrom(mList);
    mTable.Remove(key);
  }

  if (GetCacheKey(aURI, aPrincipal, false, key) &&
      mTable.Get(key, &entry)) {
    entry->removeFrom(mList);
    mTable.Remove(key);
  }
}

void
nsPreflightCache::Clear()
{
  mList.clear();
  mTable.Clear();
}

/* static */ bool
nsPreflightCache::GetCacheKey(nsIURI* aURI,
                              nsIPrincipal* aPrincipal,
                              bool aWithCredentials,
                              nsACString& _retval)
{
  NS_ASSERTION(aURI, "Null uri!");
  NS_ASSERTION(aPrincipal, "Null principal!");

  NS_NAMED_LITERAL_CSTRING(space, " ");

  nsCOMPtr<nsIURI> uri;
  nsresult rv = aPrincipal->GetURI(getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, false);

  nsAutoCString scheme, host, port;
  if (uri) {
    uri->GetScheme(scheme);
    uri->GetHost(host);
    port.AppendInt(NS_GetRealPort(uri));
  }

  if (aWithCredentials) {
    _retval.AssignLiteral("cred");
  }
  else {
    _retval.AssignLiteral("nocred");
  }

  nsAutoCString spec;
  rv = aURI->GetSpec(spec);
  NS_ENSURE_SUCCESS(rv, false);

  _retval.Append(space + scheme + space + host + space + port + space +
                 spec);

  return true;
}

//////////////////////////////////////////////////////////////////////////
// nsCORSListenerProxy

NS_IMPL_ISUPPORTS(nsCORSListenerProxy, nsIStreamListener,
                  nsIRequestObserver, nsIChannelEventSink,
                  nsIInterfaceRequestor, nsIThreadRetargetableStreamListener)

/* static */
void
nsCORSListenerProxy::Startup()
{
  Preferences::AddBoolVarCache(&gDisableCORS,
                               "content.cors.disable");
  Preferences::AddBoolVarCache(&gDisableCORSPrivateData,
                               "content.cors.no_private_data");
}

/* static */
void
nsCORSListenerProxy::Shutdown()
{
  delete sPreflightCache;
  sPreflightCache = nullptr;
}

nsCORSListenerProxy::nsCORSListenerProxy(nsIStreamListener* aOuter,
                                         nsIPrincipal* aRequestingPrincipal,
                                         bool aWithCredentials)
  : mOuterListener(aOuter),
    mRequestingPrincipal(aRequestingPrincipal),
    mOriginHeaderPrincipal(aRequestingPrincipal),
    mWithCredentials(aWithCredentials && !gDisableCORSPrivateData),
    mRequestApproved(false),
    mHasBeenCrossSite(false)
{
}

nsCORSListenerProxy::~nsCORSListenerProxy()
{
}

nsresult
nsCORSListenerProxy::Init(nsIChannel* aChannel, DataURIHandling aAllowDataURI)
{
  aChannel->GetNotificationCallbacks(getter_AddRefs(mOuterNotificationCallbacks));
  aChannel->SetNotificationCallbacks(this);

  nsresult rv = UpdateChannel(aChannel, aAllowDataURI, UpdateType::Default);
  if (NS_FAILED(rv)) {
    mOuterListener = nullptr;
    mRequestingPrincipal = nullptr;
    mOriginHeaderPrincipal = nullptr;
    mOuterNotificationCallbacks = nullptr;
  }
#ifdef DEBUG
  mInited = true;
#endif
  return rv;
}

NS_IMETHODIMP
nsCORSListenerProxy::OnStartRequest(nsIRequest* aRequest,
                                    nsISupports* aContext)
{
  MOZ_ASSERT(mInited, "nsCORSListenerProxy has not been initialized properly");
  nsresult rv = CheckRequestApproved(aRequest);
  mRequestApproved = NS_SUCCEEDED(rv);
  if (!mRequestApproved) {
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
    if (channel) {
      nsCOMPtr<nsIURI> uri;
      NS_GetFinalChannelURI(channel, getter_AddRefs(uri));
      if (uri) {
        if (sPreflightCache) {
          // OK to use mRequestingPrincipal since preflights never get
          // redirected.
          sPreflightCache->RemoveEntries(uri, mRequestingPrincipal);
        } else {
          nsCOMPtr<nsIHttpChannelChild> httpChannelChild =
            do_QueryInterface(channel);
          if (httpChannelChild) {
            rv = httpChannelChild->RemoveCorsPreflightCacheEntry(uri, mRequestingPrincipal);
            if (NS_FAILED(rv)) {
              // Only warn here to ensure we fall through the request Cancel()
              // and outer listener OnStartRequest() calls.
              NS_WARNING("Failed to remove CORS preflight cache entry!");
            }
          }
        }
      }
    }

    aRequest->Cancel(NS_ERROR_DOM_BAD_URI);
    mOuterListener->OnStartRequest(aRequest, aContext);

    return NS_ERROR_DOM_BAD_URI;
  }

  return mOuterListener->OnStartRequest(aRequest, aContext);
}

namespace {
class CheckOriginHeader final : public nsIHttpHeaderVisitor {

public:
  NS_DECL_ISUPPORTS

  CheckOriginHeader()
   : mHeaderCount(0)
  {}

  NS_IMETHOD
  VisitHeader(const nsACString & aHeader, const nsACString & aValue) override
  {
    if (aHeader.EqualsLiteral("Access-Control-Allow-Origin")) {
      mHeaderCount++;
    }

    if (mHeaderCount > 1) {
      return NS_ERROR_DOM_BAD_URI;
    }
    return NS_OK;
  }

private:
  uint32_t mHeaderCount;

  ~CheckOriginHeader()
  {}

};

NS_IMPL_ISUPPORTS(CheckOriginHeader, nsIHttpHeaderVisitor)
}

nsresult
nsCORSListenerProxy::CheckRequestApproved(nsIRequest* aRequest)
{
  // Check if this was actually a cross domain request
  if (!mHasBeenCrossSite) {
    return NS_OK;
  }

  if (gDisableCORS) {
    LogBlockedRequest(aRequest, "CORSDisabled", nullptr);
    return NS_ERROR_DOM_BAD_URI;
  }

  // Check if the request failed
  nsresult status;
  nsresult rv = aRequest->GetStatus(&status);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(status, status);

  // Test that things worked on a HTTP level
  nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(aRequest);
  if (!http) {
    LogBlockedRequest(aRequest, "CORSRequestNotHttp", nullptr);
    return NS_ERROR_DOM_BAD_URI;
  }

  nsCOMPtr<nsIHttpChannelInternal> internal = do_QueryInterface(aRequest);
  NS_ENSURE_STATE(internal);
  bool responseSynthesized = false;
  if (NS_SUCCEEDED(internal->GetResponseSynthesized(&responseSynthesized)) &&
      responseSynthesized) {
    // For synthesized responses, we don't need to perform any checks.
    // Note: This would be unsafe if we ever changed our behavior to allow
    // service workers to intercept CORS preflights.
    return NS_OK;
  }

  // Check the Access-Control-Allow-Origin header
  RefPtr<CheckOriginHeader> visitor = new CheckOriginHeader();
  nsAutoCString allowedOriginHeader;

  // check for duplicate headers
  rv = http->VisitOriginalResponseHeaders(visitor);
  if (NS_FAILED(rv)) {
    LogBlockedRequest(aRequest, "CORSAllowOriginNotMatchingOrigin", nullptr);
    return rv;
  }

  rv = http->GetResponseHeader(
    NS_LITERAL_CSTRING("Access-Control-Allow-Origin"), allowedOriginHeader);
  if (NS_FAILED(rv)) {
    LogBlockedRequest(aRequest, "CORSMissingAllowOrigin", nullptr);
    return rv;
  }

  // Bug 1210985 - Explicitly point out the error that the credential is
  // not supported if the allowing origin is '*'. Note that this check
  // has to be done before the condition
  //
  // >> if (mWithCredentials || !allowedOriginHeader.EqualsLiteral("*"))
  //
  // below since "if (A && B)" is included in "if (A || !B)".
  //
  if (mWithCredentials && allowedOriginHeader.EqualsLiteral("*")) {
    LogBlockedRequest(aRequest, "CORSNotSupportingCredentials", nullptr);
    return NS_ERROR_DOM_BAD_URI;
  }

  if (mWithCredentials || !allowedOriginHeader.EqualsLiteral("*")) {
    MOZ_ASSERT(!nsContentUtils::IsExpandedPrincipal(mOriginHeaderPrincipal));
    nsAutoCString origin;
    nsContentUtils::GetASCIIOrigin(mOriginHeaderPrincipal, origin);

    if (!allowedOriginHeader.Equals(origin)) {
      LogBlockedRequest(aRequest, "CORSAllowOriginNotMatchingOrigin",
                        NS_ConvertUTF8toUTF16(allowedOriginHeader).get());
      return NS_ERROR_DOM_BAD_URI;
    }
  }

  // Check Access-Control-Allow-Credentials header
  if (mWithCredentials) {
    nsAutoCString allowCredentialsHeader;
    rv = http->GetResponseHeader(
      NS_LITERAL_CSTRING("Access-Control-Allow-Credentials"), allowCredentialsHeader);

    if (!allowCredentialsHeader.EqualsLiteral("true")) {
      LogBlockedRequest(aRequest, "CORSMissingAllowCredentials", nullptr);
      return NS_ERROR_DOM_BAD_URI;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsCORSListenerProxy::OnStopRequest(nsIRequest* aRequest,
                                   nsISupports* aContext,
                                   nsresult aStatusCode)
{
  MOZ_ASSERT(mInited, "nsCORSListenerProxy has not been initialized properly");
  nsresult rv = mOuterListener->OnStopRequest(aRequest, aContext, aStatusCode);
  mOuterListener = nullptr;
  mOuterNotificationCallbacks = nullptr;
  return rv;
}

NS_IMETHODIMP
nsCORSListenerProxy::OnDataAvailable(nsIRequest* aRequest,
                                     nsISupports* aContext,
                                     nsIInputStream* aInputStream,
                                     uint64_t aOffset,
                                     uint32_t aCount)
{
  // NB: This can be called on any thread!  But we're guaranteed that it is
  // called between OnStartRequest and OnStopRequest, so we don't need to worry
  // about races.

  MOZ_ASSERT(mInited, "nsCORSListenerProxy has not been initialized properly");
  if (!mRequestApproved) {
    return NS_ERROR_DOM_BAD_URI;
  }
  return mOuterListener->OnDataAvailable(aRequest, aContext, aInputStream,
                                         aOffset, aCount);
}

void
nsCORSListenerProxy::SetInterceptController(nsINetworkInterceptController* aInterceptController)
{
  mInterceptController = aInterceptController;
}

NS_IMETHODIMP
nsCORSListenerProxy::GetInterface(const nsIID & aIID, void **aResult)
{
  if (aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
    *aResult = static_cast<nsIChannelEventSink*>(this);
    NS_ADDREF_THIS();

    return NS_OK;
  }

  if (aIID.Equals(NS_GET_IID(nsINetworkInterceptController)) &&
      mInterceptController) {
    nsCOMPtr<nsINetworkInterceptController> copy(mInterceptController);
    *aResult = copy.forget().take();

    return NS_OK;
  }

  return mOuterNotificationCallbacks ?
    mOuterNotificationCallbacks->GetInterface(aIID, aResult) :
    NS_ERROR_NO_INTERFACE;
}

NS_IMETHODIMP
nsCORSListenerProxy::AsyncOnChannelRedirect(nsIChannel *aOldChannel,
                                            nsIChannel *aNewChannel,
                                            uint32_t aFlags,
                                            nsIAsyncVerifyRedirectCallback *aCb)
{
  nsresult rv;
  if (NS_IsInternalSameURIRedirect(aOldChannel, aNewChannel, aFlags) ||
      NS_IsHSTSUpgradeRedirect(aOldChannel, aNewChannel, aFlags)) {
    // Internal redirects still need to be updated in order to maintain
    // the correct headers.  We use DataURIHandling::Allow, since unallowed
    // data URIs should have been blocked before we got to the internal
    // redirect.
    rv = UpdateChannel(aNewChannel, DataURIHandling::Allow,
                       UpdateType::InternalOrHSTSRedirect);
    if (NS_FAILED(rv)) {
        NS_WARNING("nsCORSListenerProxy::AsyncOnChannelRedirect: "
                   "internal redirect UpdateChannel() returned failure");
      aOldChannel->Cancel(rv);
      return rv;
    }
  } else {
    // A real, external redirect.  Perform CORS checking on new URL.
    rv = CheckRequestApproved(aOldChannel);
    if (NS_FAILED(rv)) {
      nsCOMPtr<nsIURI> oldURI;
      NS_GetFinalChannelURI(aOldChannel, getter_AddRefs(oldURI));
      if (oldURI) {
        if (sPreflightCache) {
          // OK to use mRequestingPrincipal since preflights never get
          // redirected.
          sPreflightCache->RemoveEntries(oldURI, mRequestingPrincipal);
        } else {
          nsCOMPtr<nsIHttpChannelChild> httpChannelChild =
            do_QueryInterface(aOldChannel);
          if (httpChannelChild) {
            rv = httpChannelChild->RemoveCorsPreflightCacheEntry(oldURI, mRequestingPrincipal);
            if (NS_FAILED(rv)) {
              // Only warn here to ensure we call the channel Cancel() below
              NS_WARNING("Failed to remove CORS preflight cache entry!");
            }
          }
        }
      }
      aOldChannel->Cancel(NS_ERROR_DOM_BAD_URI);
      return NS_ERROR_DOM_BAD_URI;
    }

    if (mHasBeenCrossSite) {
      // Once we've been cross-site, cross-origin redirects reset our source
      // origin. Note that we need to call GetChannelURIPrincipal() because
      // we are looking for the principal that is actually being loaded and not
      // the principal that initiated the load.
      nsCOMPtr<nsIPrincipal> oldChannelPrincipal;
      nsContentUtils::GetSecurityManager()->
        GetChannelURIPrincipal(aOldChannel, getter_AddRefs(oldChannelPrincipal));
      nsCOMPtr<nsIPrincipal> newChannelPrincipal;
      nsContentUtils::GetSecurityManager()->
        GetChannelURIPrincipal(aNewChannel, getter_AddRefs(newChannelPrincipal));
      if (!oldChannelPrincipal || !newChannelPrincipal) {
        rv = NS_ERROR_OUT_OF_MEMORY;
      }

      if (NS_SUCCEEDED(rv)) {
        bool equal;
        rv = oldChannelPrincipal->Equals(newChannelPrincipal, &equal);
        if (NS_SUCCEEDED(rv) && !equal) {
          // Spec says to set our source origin to a unique origin.
          mOriginHeaderPrincipal =
            nsNullPrincipal::CreateWithInheritedAttributes(oldChannelPrincipal);
        }
      }

      if (NS_FAILED(rv)) {
        aOldChannel->Cancel(rv);
        return rv;
      }
    }

    rv = UpdateChannel(aNewChannel, DataURIHandling::Disallow,
                       UpdateType::Default);
    if (NS_FAILED(rv)) {
        NS_WARNING("nsCORSListenerProxy::AsyncOnChannelRedirect: "
                   "UpdateChannel() returned failure");
      aOldChannel->Cancel(rv);
      return rv;
    }
  }

  nsCOMPtr<nsIChannelEventSink> outer =
    do_GetInterface(mOuterNotificationCallbacks);
  if (outer) {
    return outer->AsyncOnChannelRedirect(aOldChannel, aNewChannel, aFlags, aCb);
  }

  aCb->OnRedirectVerifyCallback(NS_OK);

  return NS_OK;
}

NS_IMETHODIMP
nsCORSListenerProxy::CheckListenerChain()
{
  MOZ_ASSERT(NS_IsMainThread());

  if (nsCOMPtr<nsIThreadRetargetableStreamListener> retargetableListener =
        do_QueryInterface(mOuterListener)) {
    return retargetableListener->CheckListenerChain();
  }

  return NS_ERROR_NO_INTERFACE;
}

// Please note that the CSP directive 'upgrade-insecure-requests' relies
// on the promise that channels get updated from http: to https: before
// the channel fetches any data from the netwerk. Such channels should
// not be blocked by CORS and marked as cross origin requests. E.g.:
// toplevel page: https://www.example.com loads
//           xhr: http://www.example.com/foo which gets updated to
//                https://www.example.com/foo
// In such a case we should bail out of CORS and rely on the promise that
// nsHttpChannel::Connect() upgrades the request from http to https.
bool
CheckUpgradeInsecureRequestsPreventsCORS(nsIPrincipal* aRequestingPrincipal,
                                         nsIChannel* aChannel)
{
  nsCOMPtr<nsIURI> channelURI;
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
  NS_ENSURE_SUCCESS(rv, false);
  bool isHttpScheme = false;
  rv = channelURI->SchemeIs("http", &isHttpScheme);
  NS_ENSURE_SUCCESS(rv, false);

  // upgrade insecure requests is only applicable to http requests
  if (!isHttpScheme) {
    return false;
  }

  nsCOMPtr<nsIURI> principalURI;
  rv = aRequestingPrincipal->GetURI(getter_AddRefs(principalURI));
  NS_ENSURE_SUCCESS(rv, false);

  // if the requestingPrincipal does not have a uri, there is nothing to do
  if (!principalURI) {
    return false;
  }

  nsCOMPtr<nsIURI>originalURI;
  rv = aChannel->GetOriginalURI(getter_AddRefs(originalURI));
  NS_ENSURE_SUCCESS(rv, false);

  nsAutoCString principalHost, channelHost, origChannelHost;

  // if we can not query a host from the uri, there is nothing to do
  if (NS_FAILED(principalURI->GetAsciiHost(principalHost)) ||
      NS_FAILED(channelURI->GetAsciiHost(channelHost)) ||
      NS_FAILED(originalURI->GetAsciiHost(origChannelHost))) {
    return false;
  }

  // if the hosts do not match, there is nothing to do
  if (!principalHost.EqualsIgnoreCase(channelHost.get())) {
    return false;
  }

  // also check that uri matches the one of the originalURI
  if (!channelHost.EqualsIgnoreCase(origChannelHost.get())) {
    return false;
  }

  nsCOMPtr<nsILoadInfo> loadInfo;
  rv = aChannel->GetLoadInfo(getter_AddRefs(loadInfo));
  NS_ENSURE_SUCCESS(rv, false);

  // lets see if the loadInfo indicates that the request will
  // be upgraded before fetching any data from the netwerk.
  return loadInfo->GetUpgradeInsecureRequests();
}


nsresult
nsCORSListenerProxy::UpdateChannel(nsIChannel* aChannel,
                                   DataURIHandling aAllowDataURI,
                                   UpdateType aUpdateType)
{
  nsCOMPtr<nsIURI> uri, originalURI;
  nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = aChannel->GetOriginalURI(getter_AddRefs(originalURI));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();

  // exempt data URIs from the same origin check.
  if (aAllowDataURI == DataURIHandling::Allow && originalURI == uri) {
    bool dataScheme = false;
    rv = uri->SchemeIs("data", &dataScheme);
    NS_ENSURE_SUCCESS(rv, rv);
    if (dataScheme) {
      return NS_OK;
    }
    if (loadInfo && loadInfo->GetAboutBlankInherits() &&
        NS_IsAboutBlank(uri)) {
      return NS_OK;
    }
  }

  // Set CORS attributes on channel so that intercepted requests get correct
  // values. We have to do this here because the CheckMayLoad checks may lead
  // to early return. We can't be sure this is an http channel though, so we
  // can't return early on failure.
  nsCOMPtr<nsIHttpChannelInternal> internal = do_QueryInterface(aChannel);
  if (internal) {
    rv = internal->SetCorsMode(nsIHttpChannelInternal::CORS_MODE_CORS);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = internal->SetCorsIncludeCredentials(mWithCredentials);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Check that the uri is ok to load
  rv = nsContentUtils::GetSecurityManager()->
    CheckLoadURIWithPrincipal(mRequestingPrincipal, uri,
                              nsIScriptSecurityManager::STANDARD);
  NS_ENSURE_SUCCESS(rv, rv);

  if (originalURI != uri) {
    rv = nsContentUtils::GetSecurityManager()->
      CheckLoadURIWithPrincipal(mRequestingPrincipal, originalURI,
                                nsIScriptSecurityManager::STANDARD);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (!mHasBeenCrossSite &&
      NS_SUCCEEDED(mRequestingPrincipal->CheckMayLoad(uri, false, false)) &&
      (originalURI == uri ||
       NS_SUCCEEDED(mRequestingPrincipal->CheckMayLoad(originalURI,
                                                       false, false)))) {
    return NS_OK;
  }

  // if the CSP directive 'upgrade-insecure-requests' is used then we should
  // not incorrectly require CORS if the only difference of a subresource
  // request and the main page is the scheme.
  // e.g. toplevel page: https://www.example.com loads
  //                xhr: http://www.example.com/somefoo,
  // then the xhr request will be upgraded to https before it fetches any data
  // from the netwerk, hence we shouldn't require CORS in that specific case.
  if (CheckUpgradeInsecureRequestsPreventsCORS(mRequestingPrincipal, aChannel)) {
    return NS_OK;
  }

  // Check if we need to do a preflight, and if so set one up. This must be
  // called once we know that the request is going, or has gone, cross-origin.
  rv = CheckPreflightNeeded(aChannel, aUpdateType);
  NS_ENSURE_SUCCESS(rv, rv);

  // It's a cross site load
  mHasBeenCrossSite = true;

  nsCString userpass;
  uri->GetUserPass(userpass);
  NS_ENSURE_TRUE(userpass.IsEmpty(), NS_ERROR_DOM_BAD_URI);

  // If we have an expanded principal here, we'll reject the CORS request,
  // because we can't send a useful Origin header which is required for CORS.
  if (nsContentUtils::IsExpandedPrincipal(mOriginHeaderPrincipal)) {
    return NS_ERROR_DOM_BAD_URI;
  }

  // Add the Origin header
  nsAutoCString origin;
  rv = nsContentUtils::GetASCIIOrigin(mOriginHeaderPrincipal, origin);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(aChannel);
  NS_ENSURE_TRUE(http, NS_ERROR_FAILURE);

  rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Origin"), origin, false);
  NS_ENSURE_SUCCESS(rv, rv);

  // Make cookie-less if needed. We don't need to do anything here if the
  // channel was opened with AsyncOpen2, since then AsyncOpen2 will take
  // care of the cookie policy for us.
  if (!mWithCredentials &&
      (!loadInfo || !loadInfo->GetEnforceSecurity())) {
    nsLoadFlags flags;
    rv = http->GetLoadFlags(&flags);
    NS_ENSURE_SUCCESS(rv, rv);

    flags |= nsIRequest::LOAD_ANONYMOUS;
    rv = http->SetLoadFlags(flags);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

nsresult
nsCORSListenerProxy::CheckPreflightNeeded(nsIChannel* aChannel, UpdateType aUpdateType)
{
  // If this caller isn't using AsyncOpen2, or if this *is* a preflight channel,
  // then we shouldn't initiate preflight for this channel.
  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
  if (!loadInfo ||
      loadInfo->GetSecurityMode() !=
        nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS ||
      loadInfo->GetIsPreflight()) {
    return NS_OK;
  }

  bool doPreflight = loadInfo->GetForcePreflight();

  nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(aChannel);
  NS_ENSURE_TRUE(http, NS_ERROR_DOM_BAD_URI);
  nsAutoCString method;
  http->GetRequestMethod(method);
  if (!method.LowerCaseEqualsLiteral("get") &&
      !method.LowerCaseEqualsLiteral("post") &&
      !method.LowerCaseEqualsLiteral("head")) {
    doPreflight = true;
  }

  // Avoid copying the array here
  const nsTArray<nsCString>& loadInfoHeaders = loadInfo->CorsUnsafeHeaders();
  if (!loadInfoHeaders.IsEmpty()) {
    doPreflight = true;
  }

  // Add Content-Type header if needed
  nsTArray<nsCString> headers;
  nsAutoCString contentTypeHeader;
  nsresult rv = http->GetRequestHeader(NS_LITERAL_CSTRING("Content-Type"),
                                       contentTypeHeader);
  // GetRequestHeader return an error if the header is not set. Don't add
  // "content-type" to the list if that's the case.
  if (NS_SUCCEEDED(rv) &&
      !nsContentUtils::IsAllowedNonCorsContentType(contentTypeHeader) &&
      !loadInfoHeaders.Contains(NS_LITERAL_CSTRING("content-type"),
                                nsCaseInsensitiveCStringArrayComparator())) {
    headers.AppendElements(loadInfoHeaders);
    headers.AppendElement(NS_LITERAL_CSTRING("content-type"));
    doPreflight = true;
  }

  if (!doPreflight) {
    return NS_OK;
  }

  // A preflight is needed. But if we've already been cross-site, then
  // we already did a preflight when that happened, and so we're not allowed
  // to do another preflight again.
  if (aUpdateType != UpdateType::InternalOrHSTSRedirect) {
    NS_ENSURE_FALSE(mHasBeenCrossSite, NS_ERROR_DOM_BAD_URI);
  }

  nsCOMPtr<nsIHttpChannelInternal> internal = do_QueryInterface(http);
  NS_ENSURE_TRUE(internal, NS_ERROR_DOM_BAD_URI);

  internal->SetCorsPreflightParameters(
    headers.IsEmpty() ? loadInfoHeaders : headers);

  return NS_OK;
}

//////////////////////////////////////////////////////////////////////////
// Preflight proxy

// Class used as streamlistener and notification callback when
// doing the initial OPTIONS request for a CORS check
class nsCORSPreflightListener final : public nsIStreamListener,
                                      public nsIInterfaceRequestor,
                                      public nsIChannelEventSink
{
public:
  nsCORSPreflightListener(nsIPrincipal* aReferrerPrincipal,
                          nsICorsPreflightCallback* aCallback,
                          nsILoadContext* aLoadContext,
                          bool aWithCredentials,
                          const nsCString& aPreflightMethod,
                          const nsTArray<nsCString>& aPreflightHeaders)
   : mPreflightMethod(aPreflightMethod),
     mPreflightHeaders(aPreflightHeaders),
     mReferrerPrincipal(aReferrerPrincipal),
     mCallback(aCallback),
     mLoadContext(aLoadContext),
     mWithCredentials(aWithCredentials)
  {
  }

  NS_DECL_ISUPPORTS
  NS_DECL_NSISTREAMLISTENER
  NS_DECL_NSIREQUESTOBSERVER
  NS_DECL_NSIINTERFACEREQUESTOR
  NS_DECL_NSICHANNELEVENTSINK

  nsresult CheckPreflightRequestApproved(nsIRequest* aRequest);

private:
  ~nsCORSPreflightListener() {}

  void AddResultToCache(nsIRequest* aRequest);

  nsCString mPreflightMethod;
  nsTArray<nsCString> mPreflightHeaders;
  nsCOMPtr<nsIPrincipal> mReferrerPrincipal;
  nsCOMPtr<nsICorsPreflightCallback> mCallback;
  nsCOMPtr<nsILoadContext> mLoadContext;
  bool mWithCredentials;
};

NS_IMPL_ISUPPORTS(nsCORSPreflightListener, nsIStreamListener,
                  nsIRequestObserver, nsIInterfaceRequestor,
                  nsIChannelEventSink)

void
nsCORSPreflightListener::AddResultToCache(nsIRequest *aRequest)
{
  nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(aRequest);
  NS_ASSERTION(http, "Request was not http");

  // The "Access-Control-Max-Age" header should return an age in seconds.
  nsAutoCString headerVal;
  http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Max-Age"),
                          headerVal);
  if (headerVal.IsEmpty()) {
    return;
  }

  // Sanitize the string. We only allow 'delta-seconds' as specified by
  // http://dev.w3.org/2006/waf/access-control (digits 0-9 with no leading or
  // trailing non-whitespace characters).
  uint32_t age = 0;
  nsCSubstring::const_char_iterator iter, end;
  headerVal.BeginReading(iter);
  headerVal.EndReading(end);
  while (iter != end) {
    if (*iter < '0' || *iter > '9') {
      return;
    }
    age = age * 10 + (*iter - '0');
    // Cap at 24 hours. This also avoids overflow
    age = std::min(age, 86400U);
    ++iter;
  }

  if (!age || !EnsurePreflightCache()) {
    return;
  }


  // String seems fine, go ahead and cache.
  // Note that we have already checked that these headers follow the correct
  // syntax.

  nsCOMPtr<nsIURI> uri;
  NS_GetFinalChannelURI(http, getter_AddRefs(uri));

  TimeStamp expirationTime = TimeStamp::NowLoRes() + TimeDuration::FromSeconds(age);

  nsPreflightCache::CacheEntry* entry =
    sPreflightCache->GetEntry(uri, mReferrerPrincipal, mWithCredentials,
                              true);
  if (!entry) {
    return;
  }

  // The "Access-Control-Allow-Methods" header contains a comma separated
  // list of method names.
  http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Methods"),
                          headerVal);

  nsCCharSeparatedTokenizer methods(headerVal, ',');
  while(methods.hasMoreTokens()) {
    const nsDependentCSubstring& method = methods.nextToken();
    if (method.IsEmpty()) {
      continue;
    }
    uint32_t i;
    for (i = 0; i < entry->mMethods.Length(); ++i) {
      if (entry->mMethods[i].token.Equals(method)) {
        entry->mMethods[i].expirationTime = expirationTime;
        break;
      }
    }
    if (i == entry->mMethods.Length()) {
      nsPreflightCache::TokenTime* newMethod =
        entry->mMethods.AppendElement();
      if (!newMethod) {
        return;
      }

      newMethod->token = method;
      newMethod->expirationTime = expirationTime;
    }
  }

  // The "Access-Control-Allow-Headers" header contains a comma separated
  // list of method names.
  http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Headers"),
                          headerVal);

  nsCCharSeparatedTokenizer headers(headerVal, ',');
  while(headers.hasMoreTokens()) {
    const nsDependentCSubstring& header = headers.nextToken();
    if (header.IsEmpty()) {
      continue;
    }
    uint32_t i;
    for (i = 0; i < entry->mHeaders.Length(); ++i) {
      if (entry->mHeaders[i].token.Equals(header)) {
        entry->mHeaders[i].expirationTime = expirationTime;
        break;
      }
    }
    if (i == entry->mHeaders.Length()) {
      nsPreflightCache::TokenTime* newHeader =
        entry->mHeaders.AppendElement();
      if (!newHeader) {
        return;
      }

      newHeader->token = header;
      newHeader->expirationTime = expirationTime;
    }
  }
}

NS_IMETHODIMP
nsCORSPreflightListener::OnStartRequest(nsIRequest *aRequest,
                                        nsISupports *aContext)
{
#ifdef DEBUG
  {
    nsCOMPtr<nsIHttpChannelInternal> internal = do_QueryInterface(aRequest);
    bool responseSynthesized = false;
    if (internal &&
        NS_SUCCEEDED(internal->GetResponseSynthesized(&responseSynthesized))) {
      // For synthesized responses, we don't need to perform any checks.
      // This would be unsafe if we ever changed our behavior to allow
      // service workers to intercept CORS preflights.
      MOZ_ASSERT(!responseSynthesized);
    }
  }
#endif

  nsresult rv = CheckPreflightRequestApproved(aRequest);

  if (NS_SUCCEEDED(rv)) {
    // Everything worked, try to cache and then fire off the actual request.
    AddResultToCache(aRequest);

    mCallback->OnPreflightSucceeded();
  } else {
    mCallback->OnPreflightFailed(rv);
  }

  return rv;
}

NS_IMETHODIMP
nsCORSPreflightListener::OnStopRequest(nsIRequest *aRequest,
                                       nsISupports *aContext,
                                       nsresult aStatus)
{
  mCallback = nullptr;
  return NS_OK;
}

/** nsIStreamListener methods **/

NS_IMETHODIMP
nsCORSPreflightListener::OnDataAvailable(nsIRequest *aRequest,
                                         nsISupports *ctxt,
                                         nsIInputStream *inStr,
                                         uint64_t sourceOffset,
                                         uint32_t count)
{
  uint32_t totalRead;
  return inStr->ReadSegments(NS_DiscardSegment, nullptr, count, &totalRead);
}

NS_IMETHODIMP
nsCORSPreflightListener::AsyncOnChannelRedirect(nsIChannel *aOldChannel,
                                                nsIChannel *aNewChannel,
                                                uint32_t aFlags,
                                                nsIAsyncVerifyRedirectCallback *callback)
{
  // Only internal redirects allowed for now.
  if (!NS_IsInternalSameURIRedirect(aOldChannel, aNewChannel, aFlags) &&
      !NS_IsHSTSUpgradeRedirect(aOldChannel, aNewChannel, aFlags))
    return NS_ERROR_DOM_BAD_URI;

  callback->OnRedirectVerifyCallback(NS_OK);
  return NS_OK;
}

nsresult
nsCORSPreflightListener::CheckPreflightRequestApproved(nsIRequest* aRequest)
{
  nsresult status;
  nsresult rv = aRequest->GetStatus(&status);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(status, status);

  // Test that things worked on a HTTP level
  nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(aRequest);
  nsCOMPtr<nsIHttpChannelInternal> internal = do_QueryInterface(aRequest);
  NS_ENSURE_STATE(internal);

  bool succeedded;
  rv = http->GetRequestSucceeded(&succeedded);
  if (NS_FAILED(rv) || !succeedded) {
    LogBlockedRequest(aRequest, "CORSPreflightDidNotSucceed", nullptr);
    return NS_ERROR_DOM_BAD_URI;
  }

  nsAutoCString headerVal;
  // The "Access-Control-Allow-Methods" header contains a comma separated
  // list of method names.
  http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Methods"),
                          headerVal);
  bool foundMethod = mPreflightMethod.EqualsLiteral("GET") ||
                       mPreflightMethod.EqualsLiteral("HEAD") ||
                       mPreflightMethod.EqualsLiteral("POST");
  nsCCharSeparatedTokenizer methodTokens(headerVal, ',');
  while(methodTokens.hasMoreTokens()) {
    const nsDependentCSubstring& method = methodTokens.nextToken();
    if (method.IsEmpty()) {
      continue;
    }
    if (!NS_IsValidHTTPToken(method)) {
      LogBlockedRequest(aRequest, "CORSInvalidAllowMethod",
                        NS_ConvertUTF8toUTF16(method).get());
      return NS_ERROR_DOM_BAD_URI;
    }
    foundMethod |= mPreflightMethod.Equals(method);
  }
  if (!foundMethod) {
    LogBlockedRequest(aRequest, "CORSMethodNotFound", nullptr);
    return NS_ERROR_DOM_BAD_URI;
  }

  // The "Access-Control-Allow-Headers" header contains a comma separated
  // list of header names.
  http->GetResponseHeader(NS_LITERAL_CSTRING("Access-Control-Allow-Headers"),
                          headerVal);
  nsTArray<nsCString> headers;
  nsCCharSeparatedTokenizer headerTokens(headerVal, ',');
  while(headerTokens.hasMoreTokens()) {
    const nsDependentCSubstring& header = headerTokens.nextToken();
    if (header.IsEmpty()) {
      continue;
    }
    if (!NS_IsValidHTTPToken(header)) {
      LogBlockedRequest(aRequest, "CORSInvalidAllowHeader",
                        NS_ConvertUTF8toUTF16(header).get());
      return NS_ERROR_DOM_BAD_URI;
    }
    headers.AppendElement(header);
  }
  for (uint32_t i = 0; i < mPreflightHeaders.Length(); ++i) {
    if (!headers.Contains(mPreflightHeaders[i],
                          nsCaseInsensitiveCStringArrayComparator())) {
      LogBlockedRequest(aRequest, "CORSMissingAllowHeaderFromPreflight",
                        NS_ConvertUTF8toUTF16(mPreflightHeaders[i]).get());
      return NS_ERROR_DOM_BAD_URI;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsCORSPreflightListener::GetInterface(const nsIID & aIID, void **aResult)
{
  if (aIID.Equals(NS_GET_IID(nsILoadContext)) && mLoadContext) {
    nsCOMPtr<nsILoadContext> copy = mLoadContext;
    copy.forget(aResult);
    return NS_OK;
  }

  return QueryInterface(aIID, aResult);
}

void
nsCORSListenerProxy::RemoveFromCorsPreflightCache(nsIURI* aURI,
                                                  nsIPrincipal* aRequestingPrincipal)
{
  MOZ_ASSERT(XRE_IsParentProcess());
  if (sPreflightCache) {
    sPreflightCache->RemoveEntries(aURI, aRequestingPrincipal);
  }
}

nsresult
nsCORSListenerProxy::StartCORSPreflight(nsIChannel* aRequestChannel,
                                        nsICorsPreflightCallback* aCallback,
                                        nsTArray<nsCString>& aUnsafeHeaders,
                                        nsIChannel** aPreflightChannel)
{
  *aPreflightChannel = nullptr;

  if (gDisableCORS) {
    LogBlockedRequest(aRequestChannel, "CORSDisabled", nullptr);
    return NS_ERROR_DOM_BAD_URI;
  }

  nsAutoCString method;
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequestChannel));
  NS_ENSURE_TRUE(httpChannel, NS_ERROR_UNEXPECTED);
  httpChannel->GetRequestMethod(method);

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_GetFinalChannelURI(aRequestChannel, getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsILoadInfo> originalLoadInfo = aRequestChannel->GetLoadInfo();
  MOZ_ASSERT(originalLoadInfo, "can not perform CORS preflight without a loadInfo");
  if (!originalLoadInfo) {
    return NS_ERROR_FAILURE;
  }

  MOZ_ASSERT(originalLoadInfo->GetSecurityMode() ==
             nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS,
             "how did we end up here?");

  nsCOMPtr<nsIPrincipal> principal = originalLoadInfo->LoadingPrincipal();
  MOZ_ASSERT(principal &&
             originalLoadInfo->GetExternalContentPolicyType() !=
               nsIContentPolicy::TYPE_DOCUMENT,
             "Should not do CORS loads for top-level loads, so a loadingPrincipal should always exist.");
  bool withCredentials = originalLoadInfo->GetCookiePolicy() ==
    nsILoadInfo::SEC_COOKIES_INCLUDE;

  nsPreflightCache::CacheEntry* entry =
    sPreflightCache ?
    sPreflightCache->GetEntry(uri, principal, withCredentials, false) :
    nullptr;

  if (entry && entry->CheckRequest(method, aUnsafeHeaders)) {
    aCallback->OnPreflightSucceeded();
    return NS_OK;
  }

  // Either it wasn't cached or the cached result has expired. Build a
  // channel for the OPTIONS request.

  nsCOMPtr<nsILoadInfo> loadInfo = static_cast<mozilla::LoadInfo*>
    (originalLoadInfo.get())->CloneForNewRequest();
  static_cast<mozilla::LoadInfo*>(loadInfo.get())->SetIsPreflight();

  nsCOMPtr<nsILoadGroup> loadGroup;
  rv = aRequestChannel->GetLoadGroup(getter_AddRefs(loadGroup));
  NS_ENSURE_SUCCESS(rv, rv);

  // We want to give the preflight channel's notification callbacks the same
  // load context as the original channel's notification callbacks had.  We
  // don't worry about a load context provided via the loadgroup here, since
  // they have the same loadgroup.
  nsCOMPtr<nsIInterfaceRequestor> callbacks;
  rv = aRequestChannel->GetNotificationCallbacks(getter_AddRefs(callbacks));
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsILoadContext> loadContext = do_GetInterface(callbacks);

  nsLoadFlags loadFlags;
  rv = aRequestChannel->GetLoadFlags(&loadFlags);
  NS_ENSURE_SUCCESS(rv, rv);

  // Preflight requests should never be intercepted by service workers and
  // are always anonymous.
  // NOTE: We ignore CORS checks on synthesized responses (see the CORS
  // preflights, then we need to extend the GetResponseSynthesized() check in
  // nsCORSListenerProxy::CheckRequestApproved()). If we change our behavior
  // here and allow service workers to intercept CORS preflights, then that
  // check won't be safe any more.
  loadFlags |= nsIChannel::LOAD_BYPASS_SERVICE_WORKER |
               nsIRequest::LOAD_ANONYMOUS;

  nsCOMPtr<nsIChannel> preflightChannel;
  rv = NS_NewChannelInternal(getter_AddRefs(preflightChannel),
                             uri,
                             loadInfo,
                             loadGroup,
                             nullptr,   // aCallbacks
                             loadFlags);
  NS_ENSURE_SUCCESS(rv, rv);

  // Set method and headers
  nsCOMPtr<nsIHttpChannel> preHttp = do_QueryInterface(preflightChannel);
  NS_ASSERTION(preHttp, "Failed to QI to nsIHttpChannel!");

  rv = preHttp->SetRequestMethod(NS_LITERAL_CSTRING("OPTIONS"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = preHttp->
    SetRequestHeader(NS_LITERAL_CSTRING("Access-Control-Request-Method"),
                     method, false);
  NS_ENSURE_SUCCESS(rv, rv);

  nsTArray<nsCString> preflightHeaders;
  if (!aUnsafeHeaders.IsEmpty()) {
    for (uint32_t i = 0; i < aUnsafeHeaders.Length(); ++i) {
      preflightHeaders.AppendElement();
      ToLowerCase(aUnsafeHeaders[i], preflightHeaders[i]);
    }
    preflightHeaders.Sort();
    nsAutoCString headers;
    for (uint32_t i = 0; i < preflightHeaders.Length(); ++i) {
      if (i != 0) {
        headers += ',';
      }
      headers += preflightHeaders[i];
    }
    rv = preHttp->
      SetRequestHeader(NS_LITERAL_CSTRING("Access-Control-Request-Headers"),
                       headers, false);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Set up listener which will start the original channel
  RefPtr<nsCORSPreflightListener> preflightListener =
    new nsCORSPreflightListener(principal, aCallback, loadContext,
                                withCredentials, method, preflightHeaders);

  rv = preflightChannel->SetNotificationCallbacks(preflightListener);
  NS_ENSURE_SUCCESS(rv, rv);

  // Start preflight
  rv = preflightChannel->AsyncOpen2(preflightListener);
  NS_ENSURE_SUCCESS(rv, rv);

  // Return newly created preflight channel
  preflightChannel.forget(aPreflightChannel);

  return NS_OK;
}