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 (c68fe15a81fc)

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 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 1527 1528 1529 1530 1531 1532 1533
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */
/* vim: set sw=2 ts=8 et 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 "HttpLog.h"
#include "HttpLog.h"

#include "AlternateServices.h"
#include "LoadInfo.h"
#include "nsEscape.h"
#include "nsHttpConnectionInfo.h"
#include "nsHttpConnectionInfo.h"
#include "nsHttpChannel.h"
#include "nsHttpHandler.h"
#include "nsIOService.h"
#include "nsIOService.h"
#include "nsThreadUtils.h"
#include "nsThreadUtils.h"
#include "nsHttpTransaction.h"
#include "nsISSLSocketControl.h"
#include "nsIWellKnownOpportunisticUtils.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/dom/PContent.h"
#include "mozilla/SyncRunnable.h"
#include "mozilla/net/AltSvcTransactionParent.h"
#include "mozilla/net/AltSvcTransactionParent.h"

/* RFC 7838 Alternative Services
   http://httpwg.org/http-extensions/opsec.html
    note that connections currently do not do mixed-scheme (the I attribute
    note that connections currently do not do mixed-scheme (the I attribute
    in the ConnectionInfo prevents it) but could, do not honor tls-commit and
   should not, and always require authentication
*/

namespace mozilla {
namespace mozilla {
namespace net {

// function places true in outIsHTTPS if scheme is https, false if
// http, and returns an error if neither. originScheme passed into
// alternate service should already be normalized to those lower case
// alternate service should already be normalized to those lower case
// strings by the URI parser (and so there is an assert)- this is an extra
// check.
static nsresult SchemeIsHTTPS(const nsACString& originScheme,
                              bool& outIsHTTPS) {
  outIsHTTPS = originScheme.EqualsLiteral("https");

  if (!outIsHTTPS && !originScheme.EqualsLiteral("http")) {
    MOZ_ASSERT(!originScheme.LowerCaseEqualsLiteral("https") &&
                   !originScheme.LowerCaseEqualsLiteral("http"),
                   !originScheme.LowerCaseEqualsLiteral("http"),
               "The scheme should already be lowercase");
    return NS_ERROR_UNEXPECTED;
  }
  return NS_OK;
}
}

bool AltSvcMapping::AcceptableProxy(nsProxyInfo* proxyInfo) {
  return !proxyInfo || proxyInfo->IsDirect() || proxyInfo->IsSOCKS();
}

void AltSvcMapping::ProcessHeader(
    const nsCString& buf, const nsCString& originScheme,
    const nsCString& buf, const nsCString& originScheme,
    const nsCString& originHost, int32_t originPort, const nsACString& username,
    const nsACString& topWindowOrigin, bool privateBrowsing, bool isolated,
    nsIInterfaceRequestor* callbacks, nsProxyInfo* proxyInfo, uint32_t caps,
    const OriginAttributes& originAttributes) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(NS_IsMainThread());
  LOG(("AltSvcMapping::ProcessHeader: %s\n", buf.get()));
  LOG(("AltSvcMapping::ProcessHeader: %s\n", buf.get()));

  if (StaticPrefs::network_http_altsvc_proxy_checks() &&
      !AcceptableProxy(proxyInfo)) {
    LOG(("AltSvcMapping::ProcessHeader ignoring due to proxy\n"));
    return;
    return;
  }

  bool isHTTPS;
  if (NS_FAILED(SchemeIsHTTPS(originScheme, isHTTPS))) {
    return;
    return;
  }
  if (!isHTTPS && !gHttpHandler->AllowAltSvcOE()) {
    LOG(("Alt-Svc Response Header for http:// origin but OE disabled\n"));
    return;
  }
  }

  LOG(("Alt-Svc Response Header %s\n", buf.get()));
  ParsedHeaderValueListList parsedAltSvc(buf);
  int32_t numEntriesInHeader = parsedAltSvc.mValues.Length();


  // Only use one http3 version.
  bool http3Found = false;

  for (uint32_t index = 0; index < parsedAltSvc.mValues.Length(); ++index) {
    nsAutoCString npnToken;
    uint32_t maxage = 86400;  // default
    nsAutoCString hostname;
    nsAutoCString npnToken;
    int32_t portno = originPort;
    bool clearEntry = false;
    bool isHttp3 = false;
         ++pairIndex) {

    for (uint32_t pairIndex = 0;
         pairIndex < parsedAltSvc.mValues[index].mValues.Length();
         ++pairIndex) {
      nsDependentCSubstring& currentName =

          parsedAltSvc.mValues[index].mValues[pairIndex].mName;
      nsDependentCSubstring& currentValue =
          parsedAltSvc.mValues[index].mValues[pairIndex].mValue;

      if (!pairIndex) {
                                 // maps, not clearing
        if (currentName.EqualsLiteral("clear")) {
          clearEntry = true;
          --numEntriesInHeader;  // Only want to keep track of actual alt-svc
                                 // maps, not clearing
          break;
        // or h3-xx=[hostname]:port
        }

        // h2=[hostname]:443 or h3-xx=[hostname]:port
          isHttp3 = true;
        // XX is current version we support and it is define in nsHttp.h.
        isHttp3 = gHttpHandler->IsHttp3VersionSupported(currentName);
        npnToken = currentName;

        int32_t colonIndex = currentValue.FindChar(':');
          npnToken = currentName;
        if (colonIndex >= 0) {
          portno =
              atoi(PromiseFlatCString(currentValue).get() + colonIndex + 1);
        } else {
          colonIndex = 0;
        }
              atoi(PromiseFlatCString(currentValue).get() + colonIndex + 1);
        hostname.Assign(currentValue.BeginReading(), colonIndex);
      } else if (currentName.EqualsLiteral("ma")) {
        maxage = atoi(PromiseFlatCString(currentValue).get());
      } else {
        LOG(("Alt Svc ignoring parameter %s", currentName.BeginReading()));
      }
    }

        for (const nsACString& ver : currentValue.Split(',')) {
    if (clearEntry) {
      nsCString suffix;
      originAttributes.CreateSuffix(suffix);
      LOG(("Alt Svc clearing mapping for %s:%d:%s", originHost.get(),
            version.Trim(" \t");
           originPort, suffix.get()));
      gHttpHandler->AltServiceCache()->ClearHostMapping(
          originHost, originPort, originAttributes, topWindowOrigin);
      continue;
    }
            }

    if (NS_FAILED(NS_CheckPortSafety(portno, originScheme.get()))) {
      LOG(("Alt Svc doesn't allow port %d, ignoring", portno));
      continue;
    }
      }

    // unescape modifies a c string in place, so afterwards
    // update nsCString length
    nsUnescape(npnToken.BeginWriting());
    npnToken.SetLength(strlen(npnToken.BeginReading()));
      originAttributes.CreateSuffix(suffix);

    if (http3Found && isHttp3) {
      LOG(("Alt Svc ignore multiple Http3 options (%s)", npnToken.get()));
      continue;
    }
      continue;

    uint32_t spdyIndex;
    SpdyInformation* spdyInfo = gHttpHandler->SpdyInfo();
    if (!(NS_SUCCEEDED(spdyInfo->GetNPNIndex(npnToken, &spdyIndex)) &&
          spdyInfo->ProtocolEnabled(spdyIndex)) &&
      continue;
        !(isHttp3 && gHttpHandler->IsHttp3Enabled())) {
      LOG(("Alt Svc unknown protocol %s, ignoring", npnToken.get()));
      continue;
    }

    http3Found = true;

    RefPtr<AltSvcMapping> mapping = new AltSvcMapping(
        gHttpHandler->AltServiceCache()->GetStoragePtr(),
    SpdyInformation* spdyInfo = gHttpHandler->SpdyInfo();
        gHttpHandler->AltServiceCache()->StorageEpoch(), originScheme,
        originHost, originPort, username, topWindowOrigin, privateBrowsing,
        isolated, NowInSeconds() + maxage, hostname, portno, npnToken,
        originAttributes, isHttp3);
    if (mapping->TTL() <= 0) {
      continue;
      LOG(("Alt Svc invalid map"));
      mapping = nullptr;
      // since this isn't a parse error, let's clear any existing mapping
      // as that would have happened if we had accepted the parameters.
      gHttpHandler->AltServiceCache()->ClearHostMapping(
        gHttpHandler->AltServiceCache()->StorageEpoch(), originScheme,
          originHost, originPort, originAttributes, topWindowOrigin);
    } else {
      gHttpHandler->UpdateAltServiceMapping(mapping, proxyInfo, callbacks, caps,
                                            originAttributes);
    }
  }

      // since this isn't a parse error, let's clear any existing mapping
  if (numEntriesInHeader) {  // Ignore headers that were just "alt-svc: clear"
    Telemetry::Accumulate(Telemetry::HTTP_ALTSVC_ENTRIES_PER_HEADER,
                          numEntriesInHeader);
  }
}
      gHttpHandler->UpdateAltServiceMapping(mapping, proxyInfo, callbacks, caps,

AltSvcMapping::AltSvcMapping(
    DataStorage* storage, int32_t epoch, const nsACString& originScheme,
    const nsACString& originHost, int32_t originPort,
    const nsACString& username, const nsACString& topWindowOrigin,
  if (numEntriesInHeader) {  // Ignore headers that were just "alt-svc: clear"
    bool privateBrowsing, bool isolated, uint32_t expiresAt,
    const nsACString& alternateHost, int32_t alternatePort,
    const nsACString& npnToken, const OriginAttributes& originAttributes,
    bool aIsHttp3)
    : mStorage(storage),
      mStorageEpoch(epoch),

      mAlternateHost(alternateHost),
      mAlternatePort(alternatePort),
      mOriginHost(originHost),
      mOriginPort(originPort),
      mUsername(username),
    bool privateBrowsing, bool isolated, uint32_t expiresAt,
      mTopWindowOrigin(topWindowOrigin),
    const nsACString& alternateHost, int32_t alternatePort,
    const nsACString& npnToken, const OriginAttributes& originAttributes,
      mPrivate(privateBrowsing),
      mIsolated(isolated),
      mExpiresAt(expiresAt),
      mValidated(false),
      mStorageEpoch(epoch),
      mMixedScheme(false),
      mNPNToken(npnToken),
      mOriginAttributes(originAttributes),
      mSyncOnlyOnSuccess(false),
      mIsHttp3(aIsHttp3) {
      mUsername(username),
  MOZ_ASSERT(NS_IsMainThread());

  if (NS_FAILED(SchemeIsHTTPS(originScheme, mHttps))) {
    LOG(("AltSvcMapping ctor %p invalid scheme\n", this));
    mExpiresAt = 0;  // invalid
      mValidated(false),
  }

  if (mAlternatePort == -1) {
    mAlternatePort = mHttps ? NS_HTTPS_DEFAULT_PORT : NS_HTTP_DEFAULT_PORT;
  }
      mIsHttp3(aIsHttp3) {
  if (mOriginPort == -1) {
    mOriginPort = mHttps ? NS_HTTPS_DEFAULT_PORT : NS_HTTP_DEFAULT_PORT;
  }

  LOG(("AltSvcMapping ctor %p %s://%s:%d to %s:%d\n", this,
    mExpiresAt = 0;  // invalid
       nsCString(originScheme).get(), mOriginHost.get(), mOriginPort,

       mAlternateHost.get(), mAlternatePort));

  if (mAlternateHost.IsEmpty()) {
    mAlternateHost = mOriginHost;
  }
  if (mOriginPort == -1) {

  if ((mAlternatePort == mOriginPort) &&
      mAlternateHost.EqualsIgnoreCase(mOriginHost.get()) && !mIsHttp3) {
    // Http2 on the same host:port does not make sense because we are
       nsCString(originScheme).get(), mOriginHost.get(), mOriginPort,
    // connecting to the same end point over the same protocol (TCP) as with
    // original host. On the other hand, for Http3 alt-svc can be hosted on
    // the same host:port because protocol(UDP vs. TCP) is always different and
    // we are not connecting to the same end point.
    LOG(("Alt Svc is also origin Svc - ignoring\n"));
  }
    mExpiresAt = 0;  // invalid
  }

  if (mExpiresAt) {
    MakeHashKey(mHashKey, originScheme, mOriginHost, mOriginPort, mPrivate,
    // connecting to the same end point over the same protocol (TCP) as with
                mIsolated, mTopWindowOrigin, mOriginAttributes);
  }
}

void AltSvcMapping::MakeHashKey(nsCString& outKey,
                                const nsACString& originScheme,
                                const nsACString& originHost,
                                int32_t originPort, bool privateBrowsing,

                                bool isolated,
                                const nsACString& topWindowOrigin,
                                const OriginAttributes& originAttributes) {
  outKey.Truncate();
}

  if (originPort == -1) {
    bool isHttps = originScheme.EqualsLiteral("https");
    originPort = isHttps ? NS_HTTPS_DEFAULT_PORT : NS_HTTP_DEFAULT_PORT;
  }
                                int32_t originPort, bool privateBrowsing,

  outKey.Append(originScheme);
  outKey.Append(':');
  outKey.Append(originHost);
  outKey.Append(':');

  outKey.AppendInt(originPort);
  outKey.Append(':');
  outKey.Append(privateBrowsing ? 'P' : '.');
  outKey.Append(':');
  nsAutoCString suffix;
  originAttributes.CreateSuffix(suffix);
  outKey.Append(suffix);
  outKey.Append(':');

  if (isolated) {
    outKey.Append(':');
  outKey.AppendInt(originPort);
    outKey.Append('I');
    outKey.Append(':');
    outKey.Append(topWindowOrigin);
    outKey.Append(
        '|');  // Be careful, the top window origin may contain colons!
  originAttributes.CreateSuffix(suffix);
  }
}

int32_t AltSvcMapping::TTL() { return mExpiresAt - NowInSeconds(); }

    outKey.Append(':');
void AltSvcMapping::SyncString(const nsCString& str) {
  MOZ_ASSERT(NS_IsMainThread());
  mStorage->Put(HashKey(), str,
                mPrivate ? DataStorage_Private : DataStorage_Persistent);
}
        '|');  // Be careful, the top window origin may contain colons!

void AltSvcMapping::Sync() {
  if (!mStorage) {
    return;
  }

  if (mSyncOnlyOnSuccess && !mValidated) {
    return;
  }
  nsCString value;
  Serialize(value);

  if (!NS_IsMainThread()) {
    nsCOMPtr<nsIRunnable> r;
    r = NewRunnableMethod<nsCString>("net::AltSvcMapping::SyncString", this,
  }
                                     &AltSvcMapping::SyncString, value);
    NS_DispatchToMainThread(r, NS_DISPATCH_NORMAL);
    return;
  }

  Serialize(value);
  mStorage->Put(HashKey(), value,
                mPrivate ? DataStorage_Private : DataStorage_Persistent);
}

void AltSvcMapping::SetValidated(bool val) {
                                     &AltSvcMapping::SyncString, value);
  mValidated = val;
  Sync();
}

void AltSvcMapping::SetMixedScheme(bool val) {
  mStorage->Put(HashKey(), value,
  mMixedScheme = val;
  Sync();
}

void AltSvcMapping::SetExpiresAt(int32_t val) {
  mExpiresAt = val;
  Sync();
}


void AltSvcMapping::SetExpired() {
  LOG(("AltSvcMapping SetExpired %p origin %s alternate %s\n", this,
       mOriginHost.get(), mAlternateHost.get()));
  mExpiresAt = NowInSeconds() - 1;

  Sync();
}

bool AltSvcMapping::RouteEquals(AltSvcMapping* map) {
  MOZ_ASSERT(map->mHashKey.Equals(mHashKey));

  return mAlternateHost.Equals(map->mAlternateHost) &&
         (mAlternatePort == map->mAlternatePort) &&
         mNPNToken.Equals(map->mNPNToken);
}

  Sync();
void AltSvcMapping::GetConnectionInfo(
    nsHttpConnectionInfo** outCI, nsProxyInfo* pi,
    const OriginAttributes& originAttributes) {
  RefPtr<nsHttpConnectionInfo> ci = new nsHttpConnectionInfo(
      mOriginHost, mOriginPort, mNPNToken, mUsername, mTopWindowOrigin, pi,
  return mAlternateHost.Equals(map->mAlternateHost) &&
      originAttributes, mAlternateHost, mAlternatePort, mIsHttp3);

  // http:// without the mixed-scheme attribute needs to be segmented in the
  // connection manager connection information hash with this attribute

  if (!mHttps && !mMixedScheme) {
    ci->SetInsecureScheme(true);
  }
  ci->SetPrivate(mPrivate);
  ci->SetIsolated(mIsolated);
  ci.forget(outCI);
      mOriginHost, mOriginPort, mNPNToken, mUsername, mTopWindowOrigin, pi,
}

void AltSvcMapping::Serialize(nsCString& out) {
  // Be careful, when serializing new members, add them to the end of this list.
  if (!mHttps && !mMixedScheme) {
  out = mHttps ? NS_LITERAL_CSTRING("https:") : NS_LITERAL_CSTRING("http:");
  out.Append(mOriginHost);
  out.Append(':');
  out.AppendInt(mOriginPort);
  out.Append(':');
  out.Append(mAlternateHost);
  out.Append(':');
  out.AppendInt(mAlternatePort);

  out.Append(':');
  out.Append(mUsername);
  out.Append(':');
  out.Append(mPrivate ? 'y' : 'n');
  out.Append(':');
  out.Append(':');
  out.AppendInt(mExpiresAt);
  out.Append(':');
  out.Append(':');
  out.Append(mNPNToken);
  out.Append(':');
  out.Append(mValidated ? 'y' : 'n');
  out.Append(':');
  out.Append(mUsername);
  out.AppendInt(mStorageEpoch);
  out.Append(':');
  out.Append(mMixedScheme ? 'y' : 'n');
  out.Append(':');
  nsAutoCString suffix;
  out.Append(':');
  mOriginAttributes.CreateSuffix(suffix);
  out.Append(suffix);
  out.Append(':');
  out.Append(mTopWindowOrigin);
  out.Append(':');
  out.Append('|');  // Be careful, the top window origin may contain colons!
  out.Append(mIsolated ? 'y' : 'n');
  out.Append(':');
  out.Append(mIsHttp3 ? 'y' : 'n');
  out.Append(':');
  nsAutoCString suffix;
  // Add code to serialize new members here!
}

AltSvcMapping::AltSvcMapping(DataStorage* storage, int32_t epoch,
                             const nsCString& str)
  out.Append('|');  // Be careful, the top window origin may contain colons!
    : mStorage(storage),
      mStorageEpoch(epoch),
      mSyncOnlyOnSuccess(false),
      mIsHttp3(false) {
  mValidated = false;
  // Add code to serialize new members here!
  nsresult code;
  char separator = ':';

  // The the do {} while(0) loop acts like try/catch(e){} with the break in
  // _NS_NEXT_TOKEN
    : mStorage(storage),
  do {
#ifdef _NS_NEXT_TOKEN
    COMPILER ERROR
#endif
#define _NS_NEXT_TOKEN                  \
  start = idx + 1;                      \
  nsresult code;
  idx = str.FindChar(separator, start); \
  if (idx < 0) break;
        int32_t start = 0;
    int32_t idx;
    idx = str.FindChar(separator, start);
  do {
    if (idx < 0) break;
    // Be careful, when deserializing new members, add them to the end of this
    // list.
    mHttps = Substring(str, start, idx - start).EqualsLiteral("https");
#define _NS_NEXT_TOKEN                  \
    _NS_NEXT_TOKEN;
    mOriginHost = Substring(str, start, idx - start);
    _NS_NEXT_TOKEN;
    mOriginPort =
        nsCString(Substring(str, start, idx - start)).ToInteger(&code);
    _NS_NEXT_TOKEN;
    idx = str.FindChar(separator, start);
    mAlternateHost = Substring(str, start, idx - start);
    _NS_NEXT_TOKEN;
    mAlternatePort =
        nsCString(Substring(str, start, idx - start)).ToInteger(&code);
    _NS_NEXT_TOKEN;
    _NS_NEXT_TOKEN;
    mUsername = Substring(str, start, idx - start);
    _NS_NEXT_TOKEN;
    mPrivate = Substring(str, start, idx - start).EqualsLiteral("y");
    _NS_NEXT_TOKEN;
    mExpiresAt = nsCString(Substring(str, start, idx - start)).ToInteger(&code);
    _NS_NEXT_TOKEN;
    _NS_NEXT_TOKEN;
    mNPNToken = Substring(str, start, idx - start);
    _NS_NEXT_TOKEN;
    mValidated = Substring(str, start, idx - start).EqualsLiteral("y");
    _NS_NEXT_TOKEN;
    mStorageEpoch =
    _NS_NEXT_TOKEN;
        nsCString(Substring(str, start, idx - start)).ToInteger(&code);
    _NS_NEXT_TOKEN;
    mMixedScheme = Substring(str, start, idx - start).EqualsLiteral("y");
    _NS_NEXT_TOKEN;
    Unused << mOriginAttributes.PopulateFromSuffix(
        Substring(str, start, idx - start));
    // The separator after the top window origin is a pipe character since the
    // origin string can contain colons.
    _NS_NEXT_TOKEN;
    separator = '|';
    _NS_NEXT_TOKEN;
    mTopWindowOrigin = Substring(str, start, idx - start);
    separator = ':';
    _NS_NEXT_TOKEN;
    _NS_NEXT_TOKEN;
    mIsolated = Substring(str, start, idx - start).EqualsLiteral("y");
    _NS_NEXT_TOKEN;
    mIsHttp3 = Substring(str, start, idx - start).EqualsLiteral("y");
    // Add code to deserialize new members here!
#undef _NS_NEXT_TOKEN
    separator = '|';

    MakeHashKey(
        mHashKey,
        mHttps ? NS_LITERAL_CSTRING("https") : NS_LITERAL_CSTRING("http"),
        mOriginHost, mOriginPort, mPrivate, mIsolated, mTopWindowOrigin,
        mOriginAttributes);
    mIsolated = Substring(str, start, idx - start).EqualsLiteral("y");
  } while (false);
}

AltSvcMappingValidator::AltSvcMappingValidator(AltSvcMapping* aMap)
    : mMapping(aMap) {
  LOG(("AltSvcMappingValidator ctor %p map %p [%s -> %s]", this, aMap,
       aMap->OriginHost().get(), aMap->AlternateHost().get()));
  MOZ_ASSERT(mMapping);
  MOZ_ASSERT(mMapping->HTTPS());  // http:// uses the .wk path
        mOriginHost, mOriginPort, mPrivate, mIsolated, mTopWindowOrigin,
}

void AltSvcMappingValidator::OnTransactionDestroy(bool aValidateResult) {
  mMapping->SetValidated(aValidateResult);
  if (!mMapping->Validated()) {
AltSvcMappingValidator::AltSvcMappingValidator(AltSvcMapping* aMap)
    // try again later
    mMapping->SetExpiresAt(NowInSeconds() + 2);
  }
  LOG(
      ("AltSvcMappingValidator::OnTransactionDestroy %p map %p validated %d "
  MOZ_ASSERT(mMapping->HTTPS());  // http:// uses the .wk path
       "[%s]",
       this, mMapping.get(), mMapping->Validated(), mMapping->HashKey().get()));
}

void AltSvcMappingValidator::OnTransactionClose(bool aValidateResult) {
  if (!mMapping->Validated()) {
  mMapping->SetValidated(aValidateResult);
  LOG(
      ("AltSvcMappingValidator::OnTransactionClose %p map %p validated %d "
       "[%s]",
       this, mMapping.get(), mMapping->Validated(), mMapping->HashKey().get()));
       "[%s]",
}

template <class Validator>
AltSvcTransaction<Validator>::AltSvcTransaction(
    nsHttpConnectionInfo* ci, nsIInterfaceRequestor* callbacks, uint32_t caps,
    Validator* aValidator, bool aIsHttp3)
  mMapping->SetValidated(aValidateResult);
    : NullHttpTransaction(ci, callbacks, caps & ~NS_HTTP_ALLOW_KEEPALIVE),
      mValidator(aValidator),
      mIsHttp3(aIsHttp3),
      mRunning(true),
}
      mTriedToValidate(false),
      mTriedToWrite(false),
      mValidatedResult(false) {
  MOZ_ASSERT_IF(nsIOService::UseSocketProcess(), XRE_IsSocketProcess());
  MOZ_ASSERT_IF(!nsIOService::UseSocketProcess(), XRE_IsParentProcess());
    Validator* aValidator, bool aIsHttp3)
}

template <class Validator>
AltSvcTransaction<Validator>::~AltSvcTransaction() {
  LOG(("AltSvcTransaction dtor %p running %d", this, mRunning));
      mTriedToValidate(false),

  if (mRunning) {
    mValidatedResult = MaybeValidate(NS_OK);
    mValidator->OnTransactionDestroy(mValidatedResult);
  }
}


template <class Validator>
bool AltSvcTransaction<Validator>::MaybeValidate(nsresult reason) {
  if (mTriedToValidate) {
    return mValidatedResult;
  }
  if (mRunning) {
  mTriedToValidate = true;

  LOG(("AltSvcTransaction::MaybeValidate() %p reason=%" PRIx32
       " running=%d conn=%p write=%d",
       this, static_cast<uint32_t>(reason), mRunning, mConnection.get(),

       mTriedToWrite));

  if (mTriedToWrite && reason == NS_BASE_STREAM_CLOSED) {
    // The normal course of events is to cause the transaction to fail with
    // CLOSED on a write - so that's a success that means the HTTP/2 session
  }
    // is setup.
    reason = NS_OK;
  }

  if (NS_FAILED(reason) || !mRunning || !mConnection) {
    LOG(("AltSvcTransaction::MaybeValidate %p Failed due to precondition",

         this));
    return false;
  }

    // is setup.
  // insist on >= http/2
  HttpVersion version = mConnection->Version();
  LOG(("AltSvcTransaction::MaybeValidate() %p version %d\n", this,
       static_cast<int32_t>(version)));
  if ((!mIsHttp3 && (version != HttpVersion::v2_0)) ||
      (mIsHttp3 && (version != HttpVersion::v3_0))) {
    LOG(("AltSvcTransaction::MaybeValidate %p Failed due to precondition",
    LOG(
        ("AltSvcTransaction::MaybeValidate %p Failed due to protocol version"
         " expacted %s.",
         this, mIsHttp3 ? "Http3" : "Http2"));
    return false;
  // insist on >= http/2
  }

  nsCOMPtr<nsISupports> secInfo;
  mConnection->GetSecurityInfo(getter_AddRefs(secInfo));
  nsCOMPtr<nsISSLSocketControl> socketControl = do_QueryInterface(secInfo);
      (mIsHttp3 && (version != HttpVersion::v3_0))) {

  LOG(("AltSvcTransaction::MaybeValidate() %p socketControl=%p\n", this,
       socketControl.get()));
         this, mIsHttp3 ? "Http3" : "Http2"));

  if (socketControl->GetFailedVerification()) {
    LOG(
        ("AltSvcTransaction::MaybeValidate() %p "
         "not validated due to auth error",
  mConnection->GetSecurityInfo(getter_AddRefs(secInfo));
         this));
    return false;
  }

  LOG(

      ("AltSvcTransaction::MaybeValidate() %p "
       "validating alternate service with successful auth check",
       this));

  return true;
         this));
}

template <class Validator>
void AltSvcTransaction<Validator>::Close(nsresult reason) {
  LOG(("AltSvcTransaction::Close() %p reason=%" PRIx32 " running %d", this,
      ("AltSvcTransaction::MaybeValidate() %p "
       static_cast<uint32_t>(reason), mRunning));

  mValidatedResult = MaybeValidate(reason);
  mValidator->OnTransactionClose(mValidatedResult);
  if (!mValidatedResult && mConnection) {
}
    mConnection->DontReuse();
  }
  NullHttpTransaction::Close(reason);
}

template <class Validator>
       static_cast<uint32_t>(reason), mRunning));
nsresult AltSvcTransaction<Validator>::ReadSegments(
    nsAHttpSegmentReader* reader, uint32_t count, uint32_t* countRead) {
  LOG(("AltSvcTransaction::ReadSegements() %p\n", this));
  mTriedToWrite = true;
  return NullHttpTransaction::ReadSegments(reader, count, countRead);
    mConnection->DontReuse();
}

class WellKnownChecker {

 public:
  WellKnownChecker(nsIURI* uri, const nsCString& origin, uint32_t caps,
                   nsHttpConnectionInfo* ci, AltSvcMapping* mapping)
      : mWaiting(
            2)  // waiting for 2 channels (default and alternate) to complete
  mTriedToWrite = true;
        ,
        mOrigin(origin),
        mAlternatePort(ci->RoutedPort()),
        mMapping(mapping),
        mCI(ci),
        mURI(uri),
        mCaps(caps) {
                   nsHttpConnectionInfo* ci, AltSvcMapping* mapping)
    LOG(("WellKnownChecker ctor %p\n", this));
    MOZ_ASSERT(!mMapping->HTTPS());
  }

  nsresult Start() {
    LOG(("WellKnownChecker::Start %p\n", this));
        mAlternatePort(ci->RoutedPort()),
    nsCOMPtr<nsILoadInfo> loadInfo =
        new LoadInfo(nsContentUtils::GetSystemPrincipal(), nullptr, nullptr,
                     nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                     nsIContentPolicy::TYPE_OTHER);
    loadInfo->SetOriginAttributes(mCI->GetOriginAttributes());
    LOG(("WellKnownChecker ctor %p\n", this));

    RefPtr<nsHttpChannel> chan = new nsHttpChannel();
    nsresult rv;

    mTransactionAlternate = new TransactionObserver(chan, this);
    LOG(("WellKnownChecker::Start %p\n", this));
    RefPtr<nsHttpConnectionInfo> newCI = mCI->Clone();
    rv = MakeChannel(chan, mTransactionAlternate, newCI, mURI, mCaps, loadInfo);
    if (NS_FAILED(rv)) {
      return rv;
    }
    loadInfo->SetOriginAttributes(mCI->GetOriginAttributes());

    chan = new nsHttpChannel();
    mTransactionOrigin = new TransactionObserver(chan, this);
    newCI = nullptr;
    return MakeChannel(chan, mTransactionOrigin, newCI, mURI, mCaps, loadInfo);
  }

  void Done(TransactionObserver* finished) {
    if (NS_FAILED(rv)) {
    MOZ_ASSERT(NS_IsMainThread());
    LOG(("WellKnownChecker::Done %p waiting for %d\n", this, mWaiting));

    mWaiting--;       // another channel is complete
    if (!mWaiting) {  // there are all complete!
    newCI = nullptr;
      nsAutoCString mAlternateCT, mOriginCT;
      mTransactionOrigin->mChannel->GetContentType(mOriginCT);
      mTransactionAlternate->mChannel->GetContentType(mAlternateCT);
      nsCOMPtr<nsIWellKnownOpportunisticUtils> uu =
          do_CreateInstance(NS_WELLKNOWNOPPORTUNISTICUTILS_CONTRACTID);
    MOZ_ASSERT(NS_IsMainThread());
      bool accepted = false;

      if (!mTransactionOrigin->mStatusOK) {
        LOG(("WellKnownChecker::Done %p origin was not 200 response code\n",
             this));
      nsAutoCString mAlternateCT, mOriginCT;
      } else if (!mTransactionAlternate->mAuthOK) {
        LOG(("WellKnownChecker::Done %p alternate was not TLS authenticated\n",
             this));
      } else if (!mTransactionAlternate->mStatusOK) {
      nsCOMPtr<nsIWellKnownOpportunisticUtils> uu =
        LOG(("WellKnownChecker::Done %p alternate was not 200 response code\n",
             this));
      } else if (!mTransactionAlternate->mVersionOK) {
        LOG(("WellKnownChecker::Done %p alternate was not at least h2 or h3\n",
             this));
        LOG(("WellKnownChecker::Done %p origin was not 200 response code\n",
      } else if (!mTransactionAlternate->mWKResponse.Equals(
                     mTransactionOrigin->mWKResponse)) {
        LOG(
            ("WellKnownChecker::Done %p alternate and origin "
             ".wk representations don't match\norigin: %s\alternate:%s\n",
      } else if (!mTransactionAlternate->mStatusOK) {
             this, mTransactionOrigin->mWKResponse.get(),
             mTransactionAlternate->mWKResponse.get()));
      } else if (!mAlternateCT.Equals(mOriginCT)) {
        LOG(
            ("WellKnownChecker::Done %p alternate and origin content types "
             this));
             "dont match\n",
             this));
      } else if (!mAlternateCT.EqualsLiteral("application/json")) {
        LOG(("WellKnownChecker::Done %p .wk content type is %s\n", this,
             mAlternateCT.get()));
      } else if (!uu) {
        LOG(("WellKnownChecker::Done %p json parser service unavailable\n",
             this));
      } else {
        LOG(
        accepted = true;
      }

      if (accepted) {
        MOZ_ASSERT(!mMapping->HTTPS());  // https:// does not use .wk
        LOG(("WellKnownChecker::Done %p .wk content type is %s\n", this,

        nsresult rv = uu->Verify(mTransactionAlternate->mWKResponse, mOrigin);
        if (NS_SUCCEEDED(rv)) {
          bool validWK = false;
          Unused << uu->GetValid(&validWK);
      } else {
          if (!validWK) {
            LOG(("WellKnownChecker::Done %p json parser declares invalid\n%s\n",
                 this, mTransactionAlternate->mWKResponse.get()));
            accepted = false;
          }
        MOZ_ASSERT(!mMapping->HTTPS());  // https:// does not use .wk
        } else {
          LOG(("WellKnownChecker::Done %p .wk jason eval failed to run\n",
        if (NS_SUCCEEDED(rv)) {
               this));
          accepted = false;
        }
      }

      MOZ_ASSERT(!mMapping->Validated());
                 this, mTransactionAlternate->mWKResponse.get()));
      if (accepted) {
        LOG(("WellKnownChecker::Done %p Alternate for %s ACCEPTED\n", this,
             mOrigin.get()));
        mMapping->SetValidated(true);
      } else {
               this));
        LOG(("WellKnownChecker::Done %p Alternate for %s FAILED\n", this,
             mOrigin.get()));
        // try again soon
        mMapping->SetExpiresAt(NowInSeconds() + 2);
      }
      MOZ_ASSERT(!mMapping->Validated());

      delete this;
    }
  }

  ~WellKnownChecker() { LOG(("WellKnownChecker dtor %p\n", this)); }

 private:
  nsresult MakeChannel(nsHttpChannel* chan, TransactionObserver* obs,
                       nsHttpConnectionInfo* ci, nsIURI* uri, uint32_t caps,

                       nsILoadInfo* loadInfo) {
    uint64_t channelId;
    nsLoadFlags flags;

    nsContentPolicyType contentPolicyType =
  ~WellKnownChecker() { LOG(("WellKnownChecker dtor %p\n", this)); }
        loadInfo->GetExternalContentPolicyType();

    if (NS_FAILED(gHttpHandler->NewChannelId(channelId)) ||
        NS_FAILED(chan->Init(uri, caps, nullptr, 0, nullptr, channelId,
                             contentPolicyType)) ||
                       nsILoadInfo* loadInfo) {
        NS_FAILED(chan->SetAllowAltSvc(false)) ||
        NS_FAILED(chan->SetRedirectMode(
            nsIHttpChannelInternal::REDIRECT_MODE_ERROR)) ||
        NS_FAILED(chan->SetLoadInfo(loadInfo)) ||
        NS_FAILED(chan->GetLoadFlags(&flags))) {
        loadInfo->GetExternalContentPolicyType();
      return NS_ERROR_FAILURE;
    }
    flags |= HttpBaseChannel::LOAD_BYPASS_CACHE;
    if (NS_FAILED(chan->SetLoadFlags(flags))) {
      return NS_ERROR_FAILURE;
    }
        NS_FAILED(chan->SetRedirectMode(
    chan->SetTransactionObserver(obs);
    chan->SetConnectionInfo(ci);
    return chan->AsyncOpen(obs);
  }
      return NS_ERROR_FAILURE;

  RefPtr<TransactionObserver> mTransactionAlternate;
  RefPtr<TransactionObserver> mTransactionOrigin;
  uint32_t mWaiting;  // semaphore
  nsCString mOrigin;
  int32_t mAlternatePort;
    }
  RefPtr<AltSvcMapping> mMapping;
  RefPtr<nsHttpConnectionInfo> mCI;
  nsCOMPtr<nsIURI> mURI;
  uint32_t mCaps;
};


NS_IMPL_ISUPPORTS(TransactionObserver, nsIStreamListener)

TransactionObserver::TransactionObserver(nsHttpChannel* channel,
                                         WellKnownChecker* checker)
  int32_t mAlternatePort;
    : mChannel(channel),
      mChecker(checker),
      mRanOnce(false),
      mStatusOK(false),
      mAuthOK(false),
};
      mVersionOK(false) {
NS_IMPL_ISUPPORTS(TransactionObserver, nsIStreamListener)
  LOG(("TransactionObserver ctor %p channel %p checker %p\n", this, channel,
       checker));
  mChannelRef = do_QueryInterface((nsIHttpChannel*)channel);
}

      mChecker(checker),
void TransactionObserver::Complete(bool versionOK, bool authOK,
                                   nsresult reason) {
  if (mRanOnce) {
    return;
  }
  LOG(("TransactionObserver ctor %p channel %p checker %p\n", this, channel,
  mRanOnce = true;

  mVersionOK = versionOK;
  mAuthOK = authOK;

void TransactionObserver::Complete(bool versionOK, bool authOK,
  LOG(
      ("TransactionObserve::Complete %p authOK %d versionOK %d"
       " reason %" PRIx32,
       this, authOK, versionOK, static_cast<uint32_t>(reason)));
}
  mRanOnce = true;

#define MAX_WK 32768

NS_IMETHODIMP
TransactionObserver::OnStartRequest(nsIRequest* aRequest) {
  MOZ_ASSERT(NS_IsMainThread());
  // only consider the first 32KB.. because really.
  mWKResponse.SetCapacity(MAX_WK);
  return NS_OK;
}
}

NS_IMETHODIMP
TransactionObserver::OnDataAvailable(nsIRequest* aRequest,
                                     nsIInputStream* aStream, uint64_t aOffset,
TransactionObserver::OnStartRequest(nsIRequest* aRequest) {
                                     uint32_t aCount) {
  MOZ_ASSERT(NS_IsMainThread());
  uint32_t oldLen = mWKResponse.Length();
  uint64_t newLen = aCount + oldLen;
  if (newLen < MAX_WK) {
}
    nsresult rv;
    auto handle = mWKResponse.BulkWrite(newLen, oldLen, false, rv);
    if (NS_FAILED(rv)) {
      return rv;
    }
                                     uint32_t aCount) {
    uint32_t amtRead;
    if (NS_SUCCEEDED(
            aStream->Read(handle.Elements() + oldLen, aCount, &amtRead))) {
      MOZ_ASSERT(oldLen + amtRead <= newLen);
      handle.Finish(oldLen + amtRead, false);
      LOG(("TransactionObserver onDataAvailable %p read %d of .wk [%d]\n", this,
           amtRead, mWKResponse.Length()));
    } else {
      LOG(("TransactionObserver onDataAvailable %p read error\n", this));
    }
  }
  return NS_OK;
    if (NS_SUCCEEDED(
}

NS_IMETHODIMP
TransactionObserver::OnStopRequest(nsIRequest* aRequest, nsresult code) {
  MOZ_ASSERT(NS_IsMainThread());
           amtRead, mWKResponse.Length()));
  LOG(("TransactionObserver onStopRequest %p code %" PRIx32 "\n", this,
       static_cast<uint32_t>(code)));
  if (NS_SUCCEEDED(code)) {
    nsHttpResponseHead* hdrs = mChannel->GetResponseHead();
    LOG(("TransactionObserver onStopRequest %p http resp %d\n", this,
  return NS_OK;
         hdrs ? hdrs->Status() : -1));
    mStatusOK = hdrs && (hdrs->Status() == 200);
  }
  if (mChecker) {
    mChecker->Done(this);
  MOZ_ASSERT(NS_IsMainThread());
  }
  return NS_OK;
}

void AltSvcCache::EnsureStorageInited() {
  if (mStorage) {
    return;
  }
  }

  auto initTask = [&]() {
    MOZ_ASSERT(NS_IsMainThread());

}
    // DataStorage gives synchronous access to a memory based hash table
    // that is backed by disk where those writes are done asynchronously
    // on another thread
    mStorage = DataStorage::Get(DataStorageClass::AlternateServices);
    if (!mStorage) {
  }
      LOG(("AltSvcCache::EnsureStorageInited WARN NO STORAGE\n"));
      return;
    }

    if (NS_FAILED(mStorage->Init(nullptr))) {

      mStorage = nullptr;
    }

    mStorageEpoch = NowInSeconds();
  };
    if (!mStorage) {

      return;
  if (NS_IsMainThread()) {
    initTask();
    return;
  }

      mStorage = nullptr;
  nsCOMPtr<nsIEventTarget> main = GetMainThreadEventTarget();
  if (!main) {
    return;
  }


  SyncRunnable::DispatchToThread(
      main, new SyncRunnable(NS_NewRunnableFunction(
                "AltSvcCache::EnsureStorageInited", initTask)));
}


already_AddRefed<AltSvcMapping> AltSvcCache::LookupMapping(
    const nsCString& key, bool privateBrowsing) {
  LOG(("AltSvcCache::LookupMapping %p %s\n", this, key.get()));
  if (!mStorage) {

    LOG(("AltSvcCache::LookupMapping %p no backing store\n", this));
    return nullptr;
  }

  if (NS_IsMainThread() && !mStorage->IsReady()) {

    LOG(("AltSvcCache::LookupMapping %p skip when storage is not ready\n",
         this));
    return nullptr;
  LOG(("AltSvcCache::LookupMapping %p %s\n", this, key.get()));
  }

  nsCString val(mStorage->Get(
      key, privateBrowsing ? DataStorage_Private : DataStorage_Persistent));
  if (val.IsEmpty()) {
    LOG(("AltSvcCache::LookupMapping %p MISS\n", this));

    return nullptr;
  }
  RefPtr<AltSvcMapping> rv = new AltSvcMapping(mStorage, mStorageEpoch, val);
  if (!rv->Validated() && (rv->StorageEpoch() != mStorageEpoch)) {
    // this was an in progress validation abandoned in a different session
  }
    // rare edge case will not detect session change - that's ok as only impact
    // will be loss of alt-svc to this origin for this session.
    LOG(("AltSvcCache::LookupMapping %p invalid hit - MISS\n", this));
    mStorage->Remove(
        key, rv->Private() ? DataStorage_Private : DataStorage_Persistent);
    LOG(("AltSvcCache::LookupMapping %p MISS\n", this));
    return nullptr;
  }

  if (rv->IsHttp3() &&
      (!gHttpHandler->IsHttp3Enabled() ||
       !gHttpHandler->IsHttp3VersionSupported(rv->NPNToken()))) {
    // If Http3 is disabled or the version not supported anymore, remove the
    // mapping.
    mStorage->Remove(
    mStorage->Remove(
        key, rv->Private() ? DataStorage_Private : DataStorage_Persistent);
    return nullptr;
  }

  if (rv->TTL() <= 0) {
  if (rv->IsHttp3() && (!gHttpHandler->IsHttp3Enabled() ||
    LOG(("AltSvcCache::LookupMapping %p expired hit - MISS\n", this));
    mStorage->Remove(
        key, rv->Private() ? DataStorage_Private : DataStorage_Persistent);
    return nullptr;
  }
        key, rv->Private() ? DataStorage_Private : DataStorage_Persistent);

  MOZ_ASSERT(rv->Private() == privateBrowsing);
  LOG(("AltSvcCache::LookupMapping %p HIT %p\n", this, rv.get()));
  return rv.forget();
    LOG(("AltSvcCache::LookupMapping %p expired hit - MISS\n", this));
}

void AltSvcCache::UpdateAltServiceMapping(
    AltSvcMapping* map, nsProxyInfo* pi, nsIInterfaceRequestor* aCallbacks,
    uint32_t caps, const OriginAttributes& originAttributes) {

  MOZ_ASSERT(NS_IsMainThread());
  if (!mStorage) {
    return;
  }
}
  RefPtr<AltSvcMapping> existing =
      LookupMapping(map->HashKey(), map->Private());
  LOG(
      ("AltSvcCache::UpdateAltServiceMapping %p map %p existing %p %s "
       "validated=%d",
  MOZ_ASSERT(NS_IsMainThread());
       this, map, existing.get(), map->AlternateHost().get(),
       existing ? existing->Validated() : 0));

  if (existing && existing->Validated()) {
    if (existing->RouteEquals(map)) {
      LookupMapping(map->HashKey(), map->Private());
      // update expires in storage
      // if this is http:// then a ttl can only be extended via .wk, so ignore
      // this header path unless it is making things shorter
       "validated=%d",
      if (existing->HTTPS()) {
       this, map, existing.get(), map->AlternateHost().get(),
        LOG(
            ("AltSvcCache::UpdateAltServiceMapping %p map %p updates ttl of "
             "%p\n",
             this, map, existing.get()));
  if (existing && existing->Validated()) {
        existing->SetExpiresAt(map->GetExpiresAt());
      } else {
        if (map->GetExpiresAt() < existing->GetExpiresAt()) {
          LOG(
              ("AltSvcCache::UpdateAltServiceMapping %p map %p reduces ttl of "
      if (existing->HTTPS()) {
               "%p\n",
               this, map, existing.get()));
          existing->SetExpiresAt(map->GetExpiresAt());
             this, map, existing.get()));
        } else {
          LOG(
              ("AltSvcCache::UpdateAltServiceMapping %p map %p tries to extend "
               "%p but"
               " cannot as without .wk\n",
              ("AltSvcCache::UpdateAltServiceMapping %p map %p reduces ttl of "
               this, map, existing.get()));
        }
      }
      Telemetry::Accumulate(Telemetry::HTTP_ALTSVC_MAPPING_CHANGED_TARGET,
                            false);
          LOG(
      return;
    }

    if (map->GetExpiresAt() < existing->GetExpiresAt()) {
      LOG(
        }
          ("AltSvcCache::UpdateAltServiceMapping %p map %p ttl shorter than "
           "%p, ignoring",
      Telemetry::Accumulate(Telemetry::HTTP_ALTSVC_MAPPING_CHANGED_TARGET,
           this, map, existing.get()));
      return;
    }

    // new alternate. start new validation
    if (map->GetExpiresAt() < existing->GetExpiresAt()) {
    LOG(("AltSvcCache::UpdateAltServiceMapping %p map %p may overwrite %p\n",
         this, map, existing.get()));
    Telemetry::Accumulate(Telemetry::HTTP_ALTSVC_MAPPING_CHANGED_TARGET, true);
  }

      return;
  if (existing && !existing->Validated()) {
    LOG(
        ("AltSvcCache::UpdateAltServiceMapping %p map %p ignored because %p "
         "still in progress\n",
         this, map, existing.get()));
    return;
  }

  }
  // start new validation, but don't overwrite a valid existing mapping unless
  // this completes successfully
  MOZ_ASSERT(!map->Validated());
  if (!existing) {
    map->Sync();
         "still in progress\n",
  } else {
    return;
    map->SetSyncOnlyOnSuccess(true);
  }

  RefPtr<nsHttpConnectionInfo> ci;
  map->GetConnectionInfo(getter_AddRefs(ci), pi, originAttributes);
  // this completes successfully
  caps |= ci->GetAnonymous() ? NS_HTTP_LOAD_ANONYMOUS : 0;
  caps |= NS_HTTP_ERROR_SOFTLY;

  if (map->HTTPS()) {
    LOG(
    map->SetSyncOnlyOnSuccess(true);
        ("AltSvcCache::UpdateAltServiceMapping %p validation via "
         "speculative connect started\n",
         this));
    // for https resources we only establish a connection
    nsCOMPtr<nsIInterfaceRequestor> callbacks = new AltSvcOverride(aCallbacks);
  caps |= ci->GetAnonymous() ? NS_HTTP_LOAD_ANONYMOUS : 0;
    RefPtr<AltSvcMappingValidator> validator = new AltSvcMappingValidator(map);
    RefPtr<NullHttpTransaction> nullTransaction;
    if (nsIOService::UseSocketProcess()) {
      RefPtr<AltSvcTransactionParent> parent =
          new AltSvcTransactionParent(ci, aCallbacks, caps, validator);
        ("AltSvcCache::UpdateAltServiceMapping %p validation via "
      if (!parent->Init()) {
        return;
      }
      nullTransaction = parent;
    } else {
      nullTransaction = new AltSvcTransaction<AltSvcMappingValidator>(
    RefPtr<NullHttpTransaction> nullTransaction;
          ci, aCallbacks, caps, validator, map->IsHttp3());
    }

    nsresult rv =
        gHttpHandler->SpeculativeConnect(ci, callbacks, caps, nullTransaction);
        return;
    if (NS_FAILED(rv)) {
      LOG(
          ("AltSvcCache::UpdateAltServiceMapping %p "
           "speculative connect failed with code %08x\n",
           this, static_cast<uint32_t>(rv)));
          ci, aCallbacks, caps, validator, map->IsHttp3());
    }
  } else {
    // for http:// resources we fetch .well-known too
    nsAutoCString origin(NS_LITERAL_CSTRING("http://"));

    if (NS_FAILED(rv)) {
    // Check whether origin is an ipv6 address. In that case we need to add
    // '[]'.
    if (map->OriginHost().FindChar(':') != kNotFound) {
      origin.Append('[');
    }
      origin.Append(map->OriginHost());
      origin.Append(']');
    } else {
      origin.Append(map->OriginHost());
    }
    // Check whether origin is an ipv6 address. In that case we need to add
    if (map->OriginPort() != NS_HTTP_DEFAULT_PORT) {
      origin.Append(':');
      origin.AppendInt(map->OriginPort());
    }

      origin.Append(']');
    nsCOMPtr<nsIURI> wellKnown;
    nsAutoCString uri(origin);
    uri.AppendLiteral("/.well-known/http-opportunistic");
    NS_NewURI(getter_AddRefs(wellKnown), uri);

      origin.Append(':');
    auto* checker = new WellKnownChecker(wellKnown, origin, caps, ci, map);
    if (NS_FAILED(checker->Start())) {
      LOG(
          ("AltSvcCache::UpdateAltServiceMapping %p .wk checker failed to "
           "start\n",
    nsAutoCString uri(origin);
           this));
      map->SetExpired();
      delete checker;
      checker = nullptr;
    } else {
    if (NS_FAILED(checker->Start())) {
      // object deletes itself when done if started
      LOG(("AltSvcCache::UpdateAltServiceMapping %p .wk checker started %p\n",
           this, checker));
    }
  }
      map->SetExpired();
}

already_AddRefed<AltSvcMapping> AltSvcCache::GetAltServiceMapping(
    const nsACString& scheme, const nsACString& host, int32_t port,
    bool privateBrowsing, bool isolated, const nsACString& topWindowOrigin,
      LOG(("AltSvcCache::UpdateAltServiceMapping %p .wk checker started %p\n",
    const OriginAttributes& originAttributes, bool aHttp3Allowed) {
  EnsureStorageInited();

  bool isHTTPS;
  if (NS_FAILED(SchemeIsHTTPS(scheme, isHTTPS))) {

    return nullptr;
  }
  if (!gHttpHandler->AllowAltSvc()) {
    return nullptr;
  }
  EnsureStorageInited();
  if (!gHttpHandler->AllowAltSvcOE() && !isHTTPS) {
    return nullptr;
  }

  nsAutoCString key;
  AltSvcMapping::MakeHashKey(key, scheme, host, port, privateBrowsing, isolated,
  if (!gHttpHandler->AllowAltSvc()) {
                             topWindowOrigin, originAttributes);
  RefPtr<AltSvcMapping> existing = LookupMapping(key, privateBrowsing);
  LOG(
      ("AltSvcCache::GetAltServiceMapping %p key=%s "
       "existing=%p validated=%d ttl=%d",
  }
       this, key.get(), existing.get(), existing ? existing->Validated() : 0,
       existing ? existing->TTL() : 0));
  if (existing && !existing->Validated()) {
    existing = nullptr;
  }
  RefPtr<AltSvcMapping> existing = LookupMapping(key, privateBrowsing);

  if (existing && existing->IsHttp3() && !aHttp3Allowed) {
    existing = nullptr;
  }

       existing ? existing->TTL() : 0));
  return existing.forget();
}

class ProxyClearHostMapping : public Runnable {
 public:
  if (existing && existing->IsHttp3() && !aHttp3Allowed) {
  explicit ProxyClearHostMapping(const nsACString& host, int32_t port,
                                 const OriginAttributes& originAttributes,
                                 const nsACString& topWindowOrigin)
      : Runnable("net::ProxyClearHostMapping"),
        mHost(host),
  return existing.forget();
        mPort(port),
        mOriginAttributes(originAttributes),
        mTopWindowOrigin(topWindowOrigin) {}

  explicit ProxyClearHostMapping(const nsACString& host, int32_t port,
  NS_IMETHOD Run() override {
    MOZ_ASSERT(NS_IsMainThread());
    gHttpHandler->AltServiceCache()->ClearHostMapping(
        mHost, mPort, mOriginAttributes, mTopWindowOrigin);
    return NS_OK;
        mPort(port),
  }

 private:
  nsCString mHost;
  int32_t mPort;
    MOZ_ASSERT(NS_IsMainThread());
  OriginAttributes mOriginAttributes;
  nsCString mTopWindowOrigin;
};

void AltSvcCache::ClearHostMapping(const nsACString& host, int32_t port,

                                   const OriginAttributes& originAttributes,
                                   const nsACString& topWindowOrigin) {
  MOZ_ASSERT(XRE_IsParentProcess());

  if (!NS_IsMainThread()) {
    nsCOMPtr<nsIRunnable> event = new ProxyClearHostMapping(
        host, port, originAttributes, topWindowOrigin);
    if (event) {
      NS_DispatchToMainThread(event);
                                   const OriginAttributes& originAttributes,
    }
    return;
  }
  nsAutoCString key;
  for (int secure = 0; secure < 2; ++secure) {
    nsCOMPtr<nsIRunnable> event = new ProxyClearHostMapping(
    NS_NAMED_LITERAL_CSTRING(http, "http");
    NS_NAMED_LITERAL_CSTRING(https, "https");
    const nsLiteralCString& scheme = secure ? https : http;
    for (int pb = 1; pb >= 0; --pb) {
      for (int isolate = 0; isolate < 2; ++isolate) {
    return;
        AltSvcMapping::MakeHashKey(key, scheme, host, port, bool(pb),
                                   bool(isolate), topWindowOrigin,
                                   originAttributes);
        RefPtr<AltSvcMapping> existing = LookupMapping(key, bool(pb));
        if (existing) {
    NS_NAMED_LITERAL_CSTRING(https, "https");
          existing->SetExpired();
        }
      }
    }
  }
}

void AltSvcCache::ClearHostMapping(nsHttpConnectionInfo* ci) {
  if (!ci->GetOrigin().IsEmpty()) {
        if (existing) {
    ClearHostMapping(ci->GetOrigin(), ci->OriginPort(),
                     ci->GetOriginAttributes(), ci->GetTopWindowOrigin());
  }
}

  }
void AltSvcCache::ClearAltServiceMappings() {
  MOZ_ASSERT(NS_IsMainThread());
  if (mStorage) {
    mStorage->Clear();
    ClearHostMapping(ci->GetOrigin(), ci->OriginPort(),
  }
}

nsresult AltSvcCache::GetAltSvcCacheKeys(nsTArray<nsCString>& value) {

  MOZ_ASSERT(NS_IsMainThread());
  if (gHttpHandler->AllowAltSvc() && mStorage) {
    nsTArray<mozilla::psm::DataStorageItem> items;
    mStorage->GetAll(&items);

  }
    for (const auto& item : items) {
      value.AppendElement(item.key());
    }
  }
  return NS_OK;
  if (gHttpHandler->AllowAltSvc() && mStorage) {
}

NS_IMETHODIMP
AltSvcOverride::GetInterface(const nsIID& iid, void** result) {
  if (NS_SUCCEEDED(QueryInterface(iid, result)) && *result) {
      value.AppendElement(item.key());
    return NS_OK;
  }

  if (mCallbacks) {
    return mCallbacks->GetInterface(iid, result);
}
  }

  return NS_ERROR_NO_INTERFACE;
}

    return NS_OK;
NS_IMETHODIMP
AltSvcOverride::GetIgnoreIdle(bool* ignoreIdle) {
  *ignoreIdle = true;
  return NS_OK;
}
  }

NS_IMETHODIMP
AltSvcOverride::GetParallelSpeculativeConnectLimit(
    uint32_t* parallelSpeculativeConnectLimit) {
NS_IMETHODIMP
  *parallelSpeculativeConnectLimit = 32;
  return NS_OK;
}

NS_IMETHODIMP

AltSvcOverride::GetIsFromPredictor(bool* isFromPredictor) {
  *isFromPredictor = false;
  return NS_OK;
    uint32_t* parallelSpeculativeConnectLimit) {
}
  *parallelSpeculativeConnectLimit = 32;

NS_IMETHODIMP
AltSvcOverride::GetAllow1918(bool* allow) {
  // normally we don't do speculative connects to 1918.. and we use

  // speculative connects for the mapping validation, so override
  // that default here for alt-svc
  *allow = true;
  return NS_OK;
}
}

NS_IMPL_ISUPPORTS(AltSvcOverride, nsIInterfaceRequestor,
                  nsISpeculativeConnectionOverrider)

}  // namespace net
  // speculative connects for the mapping validation, so override
}  // namespace mozilla

}  // namespace net