Source code

Revision control

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 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=4 sw=2 cindent et: */
/* 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/DebugOnly.h"

#include "nsIOService.h"
#include "nsIProtocolHandler.h"
#include "nsIFileProtocolHandler.h"
#include "nscore.h"
#include "nsIURI.h"
#include "prprf.h"
#include "nsErrorService.h"
#include "netCore.h"
#include "nsIObserverService.h"
#include "nsIPrefService.h"
#include "nsXPCOM.h"
#include "nsIProxiedProtocolHandler.h"
#include "nsIProxyInfo.h"
#include "nsEscape.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsCRT.h"
#include "nsSimpleNestedURI.h"
#include "nsTArray.h"
#include "nsIConsoleService.h"
#include "nsIUploadChannel2.h"
#include "nsXULAppAPI.h"
#include "nsIScriptSecurityManager.h"
#include "nsIProtocolProxyCallback.h"
#include "nsICancelable.h"
#include "nsINetworkLinkService.h"
#include "nsPISocketTransportService.h"
#include "nsAsyncRedirectVerifyHelper.h"
#include "nsURLHelper.h"
#include "nsIProtocolProxyService2.h"
#include "MainThreadUtils.h"
#include "nsINode.h"
#include "nsIWidget.h"
#include "nsThreadUtils.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/net/NeckoCommon.h"
#include "mozilla/Services.h"
#include "mozilla/Telemetry.h"
#include "mozilla/net/DNS.h"
#include "mozilla/ipc/URIUtils.h"
#include "mozilla/net/NeckoChild.h"
#include "mozilla/net/NeckoParent.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ServiceWorkerDescriptor.h"
#include "mozilla/net/CaptivePortalService.h"
#include "mozilla/net/NetworkConnectivityService.h"
#include "mozilla/net/SocketProcessHost.h"
#include "mozilla/net/SocketProcessParent.h"
#include "mozilla/Unused.h"
#include "ReferrerPolicy.h"
#include "nsContentSecurityManager.h"
#include "nsContentUtils.h"

namespace mozilla {
namespace net {

using mozilla::Maybe;
using mozilla::dom::ClientInfo;
using mozilla::dom::ServiceWorkerDescriptor;

#define PORT_PREF_PREFIX "network.security.ports."
#define PORT_PREF(x) PORT_PREF_PREFIX x
#define MANAGE_OFFLINE_STATUS_PREF "network.manage-offline-status"
#define OFFLINE_MIRRORS_CONNECTIVITY "network.offline-mirrors-connectivity"

// Nb: these have been misnomers since bug 715770 removed the buffer cache.
// "network.segment.count" and "network.segment.size" would be better names,
// but the old names are still used to preserve backward compatibility.
#define NECKO_BUFFER_CACHE_COUNT_PREF "network.buffer.cache.count"
#define NECKO_BUFFER_CACHE_SIZE_PREF "network.buffer.cache.size"
#define NETWORK_NOTIFY_CHANGED_PREF "network.notify.changed"
#define NETWORK_CAPTIVE_PORTAL_PREF "network.captive-portal-service.enabled"
#define WEBRTC_PREF_PREFIX "media.peerconnection."

#define MAX_RECURSION_COUNT 50

nsIOService *gIOService;
static bool gHasWarnedUploadChannel2;
static bool gCaptivePortalEnabled = false;
static LazyLogModule gIOServiceLog("nsIOService");
#undef LOG
#define LOG(args) MOZ_LOG(gIOServiceLog, LogLevel::Debug, args)

// A general port blacklist.  Connections to these ports will not be allowed
// unless the protocol overrides.
//
// TODO: I am sure that there are more ports to be added.
//       This cut is based on the classic mozilla codebase

int16_t gBadPortList[] = {
    1,     // tcpmux
    7,     // echo
    9,     // discard
    11,    // systat
    13,    // daytime
    15,    // netstat
    17,    // qotd
    19,    // chargen
    20,    // ftp-data
    21,    // ftp
    22,    // ssh
    23,    // telnet
    25,    // smtp
    37,    // time
    42,    // name
    43,    // nicname
    53,    // domain
    77,    // priv-rjs
    79,    // finger
    87,    // ttylink
    95,    // supdup
    101,   // hostriame
    102,   // iso-tsap
    103,   // gppitnp
    104,   // acr-nema
    109,   // pop2
    110,   // pop3
    111,   // sunrpc
    113,   // auth
    115,   // sftp
    117,   // uucp-path
    119,   // nntp
    123,   // ntp
    135,   // loc-srv / epmap
    139,   // netbios
    143,   // imap2
    179,   // bgp
    389,   // ldap
    427,   // afp (alternate)
    465,   // smtp (alternate)
    512,   // print / exec
    513,   // login
    514,   // shell
    515,   // printer
    526,   // tempo
    530,   // courier
    531,   // chat
    532,   // netnews
    540,   // uucp
    548,   // afp
    556,   // remotefs
    563,   // nntp+ssl
    587,   // smtp (outgoing)
    601,   // syslog-conn
    636,   // ldap+ssl
    993,   // imap+ssl
    995,   // pop3+ssl
    2049,  // nfs
    3659,  // apple-sasl
    4045,  // lockd
    6000,  // x11
    6665,  // irc (alternate)
    6666,  // irc (alternate)
    6667,  // irc (default)
    6668,  // irc (alternate)
    6669,  // irc (alternate)
    6697,  // irc+tls
    0,     // Sentinel value: This MUST be zero
};

static const char kProfileChangeNetTeardownTopic[] =
    "profile-change-net-teardown";
static const char kProfileChangeNetRestoreTopic[] =
    "profile-change-net-restore";
static const char kProfileDoChange[] = "profile-do-change";

// Necko buffer defaults
uint32_t nsIOService::gDefaultSegmentSize = 4096;
uint32_t nsIOService::gDefaultSegmentCount = 24;

bool nsIOService::sIsDataURIUniqueOpaqueOrigin = false;
bool nsIOService::sBlockToplevelDataUriNavigations = false;
bool nsIOService::sBlockFTPSubresources = false;

////////////////////////////////////////////////////////////////////////////////

nsIOService::nsIOService()
    : mOffline(true),
      mOfflineForProfileChange(false),
      mManageLinkStatus(false),
      mConnectivity(true),
      mOfflineMirrorsConnectivity(true),
      mSettingOffline(false),
      mSetOfflineValue(false),
      mSocketProcessLaunchComplete(false),
      mShutdown(false),
      mHttpHandlerAlreadyShutingDown(false),
      mNetworkLinkServiceInitialized(false),
      mChannelEventSinks(NS_CHANNEL_EVENT_SINK_CATEGORY),
      mNetworkNotifyChanged(true),
      mTotalRequests(0),
      mCacheWon(0),
      mNetWon(0),
      mLastOfflineStateChange(PR_IntervalNow()),
      mLastConnectivityChange(PR_IntervalNow()),
      mLastNetworkLinkChange(PR_IntervalNow()),
      mNetTearingDownStarted(0),
      mSocketProcess(nullptr) {}

static const char *gCallbackPrefs[] = {
    PORT_PREF_PREFIX,
    MANAGE_OFFLINE_STATUS_PREF,
    NECKO_BUFFER_CACHE_COUNT_PREF,
    NECKO_BUFFER_CACHE_SIZE_PREF,
    NETWORK_NOTIFY_CHANGED_PREF,
    NETWORK_CAPTIVE_PORTAL_PREF,
    nullptr,
};

static const char *gCallbackPrefsForSocketProcess[] = {
    WEBRTC_PREF_PREFIX,
    nullptr,
};

nsresult nsIOService::Init() {
  // XXX hack until xpidl supports error info directly (bug 13423)
  nsCOMPtr<nsIErrorService> errorService = nsErrorService::GetOrCreate();
  MOZ_ALWAYS_TRUE(errorService);
  errorService->RegisterErrorStringBundle(NS_ERROR_MODULE_NETWORK,
                                          NECKO_MSGS_URL);

  InitializeCaptivePortalService();

  // setup our bad port list stuff
  for (int i = 0; gBadPortList[i]; i++)
    mRestrictedPortList.AppendElement(gBadPortList[i]);

  // Further modifications to the port list come from prefs
  Preferences::RegisterPrefixCallbacks(
      PREF_CHANGE_METHOD(nsIOService::PrefsChanged), gCallbackPrefs, this);
  PrefsChanged();

  // Register for profile change notifications
  nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  if (observerService) {
    observerService->AddObserver(this, kProfileChangeNetTeardownTopic, true);
    observerService->AddObserver(this, kProfileChangeNetRestoreTopic, true);
    observerService->AddObserver(this, kProfileDoChange, true);
    observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, true);
    observerService->AddObserver(this, NS_NETWORK_LINK_TOPIC, true);
    observerService->AddObserver(this, NS_WIDGET_WAKE_OBSERVER_TOPIC, true);
    observerService->AddObserver(this, NS_PREFSERVICE_READ_TOPIC_ID, true);
  } else
    NS_WARNING("failed to get observer service");

  Preferences::AddBoolVarCache(&sIsDataURIUniqueOpaqueOrigin,
                               "security.data_uri.unique_opaque_origin", false);
  Preferences::AddBoolVarCache(
      &sBlockToplevelDataUriNavigations,
      "security.data_uri.block_toplevel_data_uri_navigations", false);
  Preferences::AddBoolVarCache(&sBlockFTPSubresources,
                               "security.block_ftp_subresources", true);
  Preferences::AddBoolVarCache(&mOfflineMirrorsConnectivity,
                               OFFLINE_MIRRORS_CONNECTIVITY, true);

  gIOService = this;

  InitializeNetworkLinkService();
  InitializeProtocolProxyService();

  SetOffline(false);

  return NS_OK;
}

nsIOService::~nsIOService() {
  if (gIOService) {
    MOZ_ASSERT(gIOService == this);
    gIOService = nullptr;
  }
}

nsresult nsIOService::InitializeCaptivePortalService() {
  if (XRE_GetProcessType() != GeckoProcessType_Default) {
    // We only initalize a captive portal service in the main process
    return NS_OK;
  }

  mCaptivePortalService = do_GetService(NS_CAPTIVEPORTAL_CID);
  if (mCaptivePortalService) {
    return static_cast<CaptivePortalService *>(mCaptivePortalService.get())
        ->Initialize();
  }

  RefPtr<NetworkConnectivityService> ncs =
      NetworkConnectivityService::GetSingleton();
  ncs->Init();

  return NS_OK;
}

nsresult nsIOService::InitializeSocketTransportService() {
  nsresult rv = NS_OK;

  if (!mSocketTransportService) {
    mSocketTransportService =
        do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
    if (NS_FAILED(rv)) {
      NS_WARNING("failed to get socket transport service");
    }
  }

  if (mSocketTransportService) {
    rv = mSocketTransportService->Init();
    NS_ASSERTION(NS_SUCCEEDED(rv), "socket transport service init failed");
    mSocketTransportService->SetOffline(false);
  }

  return rv;
}

nsresult nsIOService::InitializeNetworkLinkService() {
  nsresult rv = NS_OK;

  if (mNetworkLinkServiceInitialized) return rv;

  if (!NS_IsMainThread()) {
    NS_WARNING("Network link service should be created on main thread");
    return NS_ERROR_FAILURE;
  }

  // go into managed mode if we can, and chrome process
  if (XRE_IsParentProcess()) {
    mNetworkLinkService =
        do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID, &rv);
  }

  if (mNetworkLinkService) {
    mNetworkLinkServiceInitialized = true;
  }

  // After initializing the networkLinkService, query the connectivity state
  OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN);

  return rv;
}

nsresult nsIOService::InitializeProtocolProxyService() {
  nsresult rv = NS_OK;

  if (XRE_IsParentProcess()) {
    // for early-initialization
    Unused << do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID, &rv);
  }

  return rv;
}

already_AddRefed<nsIOService> nsIOService::GetInstance() {
  if (!gIOService) {
    RefPtr<nsIOService> ios = new nsIOService();
    if (NS_SUCCEEDED(ios->Init())) {
      MOZ_ASSERT(gIOService == ios.get());
      return ios.forget();
    }
  }
  return do_AddRef(gIOService);
}

class SocketProcessListenerProxy : public SocketProcessHost::Listener {
 public:
  SocketProcessListenerProxy() = default;
  void OnProcessLaunchComplete(SocketProcessHost *aHost, bool aSucceeded) {
    if (!gIOService) {
      return;
    }

    gIOService->OnProcessLaunchComplete(aHost, aSucceeded);
  }

  void OnProcessUnexpectedShutdown(SocketProcessHost *aHost) {
    if (!gIOService) {
      return;
    }

    gIOService->OnProcessUnexpectedShutdown(aHost);
  }
};

nsresult nsIOService::LaunchSocketProcess() {
  MOZ_ASSERT(NS_IsMainThread());

  if (XRE_GetProcessType() != GeckoProcessType_Default) {
    return NS_OK;
  }

  if (mSocketProcess) {
    return NS_OK;
  }

  if (!Preferences::GetBool("network.process.enabled", true)) {
    LOG(("nsIOService skipping LaunchSocketProcess because of the pref"));
    return NS_OK;
  }

  Preferences::RegisterPrefixCallbacks(
      PREF_CHANGE_METHOD(nsIOService::NotifySocketProcessPrefsChanged),
      gCallbackPrefsForSocketProcess, this);

  // The subprocess is launched asynchronously, so we wait for a callback to
  // acquire the IPDL actor.
  mSocketProcess = new SocketProcessHost(new SocketProcessListenerProxy());
  LOG(("nsIOService::LaunchSocketProcess"));
  if (!mSocketProcess->Launch()) {
    NS_WARNING("Failed to launch socket process!!");
    DestroySocketProcess();
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

void nsIOService::DestroySocketProcess() {
  MOZ_ASSERT(NS_IsMainThread());

  if (XRE_GetProcessType() != GeckoProcessType_Default || !mSocketProcess) {
    return;
  }

  Preferences::UnregisterPrefixCallbacks(
      PREF_CHANGE_METHOD(nsIOService::NotifySocketProcessPrefsChanged),
      gCallbackPrefsForSocketProcess, this);

  mSocketProcess->Shutdown();
  mSocketProcess = nullptr;
}

bool nsIOService::SocketProcessReady() {
  return mSocketProcess && mSocketProcess->IsConnected();
}

void nsIOService::NotifySocketProcessPrefsChanged(const char *aName) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!XRE_IsParentProcess()) {
    return;
  }

  dom::Pref pref(nsCString(aName), /* isLocked */ false, Nothing(), Nothing());
  Preferences::GetPreference(&pref);
  auto sendPrefUpdate = [pref]() {
    Unused << gIOService->mSocketProcess->GetActor()->SendPreferenceUpdate(
        pref);
  };
  CallOrWaitForSocketProcess(sendPrefUpdate);
}

void nsIOService::OnProcessLaunchComplete(SocketProcessHost *aHost,
                                          bool aSucceeded) {
  MOZ_ASSERT(NS_IsMainThread());

  LOG(("nsIOService::OnProcessLaunchComplete aSucceeded=%d\n", aSucceeded));

  mSocketProcessLaunchComplete = true;

  if (mShutdown || !SocketProcessReady()) {
    return;
  }

  if (!mPendingEvents.IsEmpty()) {
    nsTArray<std::function<void()>> pendingEvents;
    mPendingEvents.SwapElements(pendingEvents);
    for (auto &func : pendingEvents) {
      func();
    }
  }
}

void nsIOService::CallOrWaitForSocketProcess(
    const std::function<void()> &aFunc) {
  MOZ_ASSERT(NS_IsMainThread());
  if (IsSocketProcessLaunchComplete() && SocketProcessReady()) {
    aFunc();
  } else {
    mPendingEvents.AppendElement(aFunc);  // infallible
  }
}

int32_t nsIOService::SocketProcessPid() {
  if (!mSocketProcess) {
    return 0;
  }
  if (SocketProcessParent *actor = mSocketProcess->GetActor()) {
    return (int32_t)actor->OtherPid();
  }
  return 0;
}

bool nsIOService::IsSocketProcessLaunchComplete() {
  MOZ_ASSERT(NS_IsMainThread());
  return mSocketProcessLaunchComplete;
}

void nsIOService::OnProcessUnexpectedShutdown(SocketProcessHost *aHost) {
  MOZ_ASSERT(NS_IsMainThread());

  LOG(("nsIOService::OnProcessUnexpectedShutdown\n"));
  DestroySocketProcess();
}

RefPtr<MemoryReportingProcess> nsIOService::GetSocketProcessMemoryReporter() {
  // Check the prefs here again, since we don't want to create
  // SocketProcessMemoryReporter for some tests.
  if (!Preferences::GetBool("network.process.enabled") ||
      !SocketProcessReady()) {
    return nullptr;
  }

  return new SocketProcessMemoryReporter();
}

NS_IMETHODIMP
nsIOService::SocketProcessTelemetryPing() {
  CallOrWaitForSocketProcess([]() {
    Unused << gIOService->mSocketProcess->GetActor()
                  ->SendSocketProcessTelemetryPing();
  });
  return NS_OK;
}

NS_IMPL_ISUPPORTS(nsIOService, nsIIOService, nsINetUtil, nsISpeculativeConnect,
                  nsIObserver, nsIIOServiceInternal, nsISupportsWeakReference)

////////////////////////////////////////////////////////////////////////////////

nsresult nsIOService::RecheckCaptivePortal() {
  MOZ_ASSERT(NS_IsMainThread(), "Must be called on the main thread");
  if (!mCaptivePortalService) {
    return NS_OK;
  }
  nsCOMPtr<nsIRunnable> task = NewRunnableMethod(
      "nsIOService::RecheckCaptivePortal", mCaptivePortalService,
      &nsICaptivePortalService::RecheckCaptivePortal);
  return NS_DispatchToMainThread(task);
}

nsresult nsIOService::RecheckCaptivePortalIfLocalRedirect(nsIChannel *newChan) {
  nsresult rv;

  if (!mCaptivePortalService) {
    return NS_OK;
  }

  nsCOMPtr<nsIURI> uri;
  rv = newChan->GetURI(getter_AddRefs(uri));
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsCString host;
  rv = uri->GetHost(host);
  if (NS_FAILED(rv)) {
    return rv;
  }

  PRNetAddr prAddr;
  if (PR_StringToNetAddr(host.BeginReading(), &prAddr) != PR_SUCCESS) {
    // The redirect wasn't to an IP literal, so there's probably no need
    // to trigger the captive portal detection right now. It can wait.
    return NS_OK;
  }

  NetAddr netAddr;
  PRNetAddrToNetAddr(&prAddr, &netAddr);
  if (IsIPAddrLocal(&netAddr)) {
    // Redirects to local IP addresses are probably captive portals
    RecheckCaptivePortal();
  }

  return NS_OK;
}

nsresult nsIOService::AsyncOnChannelRedirect(
    nsIChannel *oldChan, nsIChannel *newChan, uint32_t flags,
    nsAsyncRedirectVerifyHelper *helper) {
  // If a redirect to a local network address occurs, then chances are we
  // are in a captive portal, so we trigger a recheck.
  RecheckCaptivePortalIfLocalRedirect(newChan);

  // This is silly. I wish there was a simpler way to get at the global
  // reference of the contentSecurityManager. But it lives in the XPCOM
  // service registry.
  nsCOMPtr<nsIChannelEventSink> sink =
      do_GetService(NS_CONTENTSECURITYMANAGER_CONTRACTID);
  if (sink) {
    nsresult rv =
        helper->DelegateOnChannelRedirect(sink, oldChan, newChan, flags);
    if (NS_FAILED(rv)) return rv;
  }

  // Finally, our category
  nsCOMArray<nsIChannelEventSink> entries;
  mChannelEventSinks.GetEntries(entries);
  int32_t len = entries.Count();
  for (int32_t i = 0; i < len; ++i) {
    nsresult rv =
        helper->DelegateOnChannelRedirect(entries[i], oldChan, newChan, flags);
    if (NS_FAILED(rv)) return rv;
  }
  return NS_OK;
}

nsresult nsIOService::CacheProtocolHandler(const char *scheme,
                                           nsIProtocolHandler *handler) {
  MOZ_ASSERT(NS_IsMainThread());

  for (unsigned int i = 0; i < NS_N(gScheme); i++) {
    if (!nsCRT::strcasecmp(scheme, gScheme[i])) {
      nsresult rv;
      NS_ASSERTION(!mWeakHandler[i], "Protocol handler already cached");
      // Make sure the handler supports weak references.
      nsCOMPtr<nsISupportsWeakReference> factoryPtr =
          do_QueryInterface(handler, &rv);
      if (!factoryPtr) {
        // Don't cache handlers that don't support weak reference as
        // there is real danger of a circular reference.
#ifdef DEBUG_dp
        printf(
            "DEBUG: %s protcol handler doesn't support weak ref. Not cached.\n",
            scheme);
#endif /* DEBUG_dp */
        return NS_ERROR_FAILURE;
      }
      mWeakHandler[i] = do_GetWeakReference(handler);
      return NS_OK;
    }
  }
  return NS_ERROR_FAILURE;
}

nsresult nsIOService::GetCachedProtocolHandler(const char *scheme,
                                               nsIProtocolHandler **result,
                                               uint32_t start, uint32_t end) {
  MOZ_ASSERT(NS_IsMainThread());

  uint32_t len = end - start - 1;
  for (unsigned int i = 0; i < NS_N(gScheme); i++) {
    if (!mWeakHandler[i]) continue;

    // handle unterminated strings
    // start is inclusive, end is exclusive, len = end - start - 1
    if (end ? (!nsCRT::strncasecmp(scheme + start, gScheme[i], len) &&
               gScheme[i][len] == '\0')
            : (!nsCRT::strcasecmp(scheme, gScheme[i]))) {
      return CallQueryReferent(mWeakHandler[i].get(), result);
    }
  }
  return NS_ERROR_FAILURE;
}

static bool UsesExternalProtocolHandler(const char *aScheme) {
  if (NS_LITERAL_CSTRING("file").Equals(aScheme) ||
      NS_LITERAL_CSTRING("chrome").Equals(aScheme) ||
      NS_LITERAL_CSTRING("resource").Equals(aScheme)) {
    // Don't allow file:, chrome: or resource: URIs to be handled with
    // nsExternalProtocolHandler, since internally we rely on being able to
    // use and read from these URIs.
    return false;
  }

  for (const auto &forcedExternalScheme : gForcedExternalSchemes) {
    if (!nsCRT::strcasecmp(forcedExternalScheme, aScheme)) {
      return true;
    }
  }

  nsAutoCString pref("network.protocol-handler.external.");
  pref += aScheme;

  return Preferences::GetBool(pref.get(), false);
}

NS_IMETHODIMP
nsIOService::GetProtocolHandler(const char *scheme,
                                nsIProtocolHandler **result) {
  nsresult rv;

  NS_ENSURE_ARG_POINTER(scheme);
  // XXX we may want to speed this up by introducing our own protocol
  // scheme -> protocol handler mapping, avoiding the string manipulation
  // and service manager stuff

  rv = GetCachedProtocolHandler(scheme, result);
  if (NS_SUCCEEDED(rv)) return rv;

  if (scheme[0] != '\0' && !UsesExternalProtocolHandler(scheme)) {
    nsAutoCString contractID(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX);
    contractID += scheme;
    ToLowerCase(contractID);

    rv = CallGetService(contractID.get(), result);
    if (NS_SUCCEEDED(rv)) {
      CacheProtocolHandler(scheme, *result);
      return rv;
    }

#ifdef MOZ_WIDGET_GTK
    // check to see whether GVFS can handle this URI scheme.  if it can
    // create a nsIURI for the "scheme:", then we assume it has support for
    // the requested protocol.  otherwise, we failover to using the default
    // protocol handler.

    rv =
        CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "moz-gio", result);
    if (NS_SUCCEEDED(rv)) {
      nsAutoCString spec(scheme);
      spec.Append(':');

      nsCOMPtr<nsIURI> uri;
      rv = (*result)->NewURI(spec, nullptr, nullptr, getter_AddRefs(uri));
      if (NS_SUCCEEDED(rv)) {
        return rv;
      }

      NS_RELEASE(*result);
    }
#endif
  }

  // Okay we don't have a protocol handler to handle this url type, so use
  // the default protocol handler.  This will cause urls to get dispatched
  // out to the OS ('cause we can't do anything with them) when we try to
  // read from a channel created by the default protocol handler.

  rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "default", result);
  if (NS_FAILED(rv)) return NS_ERROR_UNKNOWN_PROTOCOL;

  return rv;
}

NS_IMETHODIMP
nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme) {
  return net_ExtractURLScheme(inURI, scheme);
}

NS_IMETHODIMP
nsIOService::HostnameIsLocalIPAddress(nsIURI *aURI, bool *aResult) {
  NS_ENSURE_ARG_POINTER(aURI);

  nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aURI);
  NS_ENSURE_ARG_POINTER(innerURI);

  nsAutoCString host;
  nsresult rv = innerURI->GetAsciiHost(host);
  if (NS_FAILED(rv)) {
    return rv;
  }

  *aResult = false;

  PRNetAddr addr;
  PRStatus result = PR_StringToNetAddr(host.get(), &addr);
  if (result == PR_SUCCESS) {
    NetAddr netAddr;
    PRNetAddrToNetAddr(&addr, &netAddr);
    if (IsIPAddrLocal(&netAddr)) {
      *aResult = true;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsIOService::GetProtocolFlags(const char *scheme, uint32_t *flags) {
  nsCOMPtr<nsIProtocolHandler> handler;
  nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
  if (NS_FAILED(rv)) return rv;

  // We can't call DoGetProtocolFlags here because we don't have a URI. This
  // API is used by (and only used by) extensions, which is why it's still
  // around. Calling this on a scheme with dynamic flags will throw.
  rv = handler->GetProtocolFlags(flags);
#if !IS_ORIGIN_IS_FULL_SPEC_DEFINED
  MOZ_RELEASE_ASSERT(!(*flags & nsIProtocolHandler::ORIGIN_IS_FULL_SPEC),
                     "ORIGIN_IS_FULL_SPEC is unsupported but used");
#endif
  return rv;
}

class AutoIncrement {
 public:
  explicit AutoIncrement(uint32_t *var) : mVar(var) { ++*var; }
  ~AutoIncrement() { --*mVar; }

 private:
  uint32_t *mVar;
};

nsresult nsIOService::NewURI(const nsACString &aSpec, const char *aCharset,
                             nsIURI *aBaseURI, nsIURI **result) {
  NS_ASSERTION(NS_IsMainThread(), "wrong thread");

  static uint32_t recursionCount = 0;
  if (recursionCount >= MAX_RECURSION_COUNT) return NS_ERROR_MALFORMED_URI;
  AutoIncrement inc(&recursionCount);

  nsAutoCString scheme;
  nsresult rv = ExtractScheme(aSpec, scheme);
  if (NS_FAILED(rv)) {
    // then aSpec is relative
    if (!aBaseURI) return NS_ERROR_MALFORMED_URI;

    if (!aSpec.IsEmpty() && aSpec[0] == '#') {
      // Looks like a reference instead of a fully-specified URI.
      // --> initialize |uri| as a clone of |aBaseURI|, with ref appended.
      return NS_GetURIWithNewRef(aBaseURI, aSpec, result);
    }

    rv = aBaseURI->GetScheme(scheme);
    if (NS_FAILED(rv)) return rv;
  }

  // now get the handler for this scheme
  nsCOMPtr<nsIProtocolHandler> handler;
  rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  if (NS_FAILED(rv)) return rv;

  return handler->NewURI(aSpec, aCharset, aBaseURI, result);
}

NS_IMETHODIMP
nsIOService::NewFileURI(nsIFile *file, nsIURI **result) {
  nsresult rv;
  NS_ENSURE_ARG_POINTER(file);

  nsCOMPtr<nsIProtocolHandler> handler;

  rv = GetProtocolHandler("file", getter_AddRefs(handler));
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIFileProtocolHandler> fileHandler(do_QueryInterface(handler, &rv));
  if (NS_FAILED(rv)) return rv;

  return fileHandler->NewFileURI(file, result);
}

NS_IMETHODIMP
nsIOService::NewChannelFromURI(nsIURI *aURI, nsINode *aLoadingNode,
                               nsIPrincipal *aLoadingPrincipal,
                               nsIPrincipal *aTriggeringPrincipal,
                               uint32_t aSecurityFlags,
                               uint32_t aContentPolicyType,
                               nsIChannel **result) {
  return NewChannelFromURIWithProxyFlags(aURI,
                                         nullptr,  // aProxyURI
                                         0,        // aProxyFlags
                                         aLoadingNode, aLoadingPrincipal,
                                         aTriggeringPrincipal, aSecurityFlags,
                                         aContentPolicyType, result);
}
nsresult nsIOService::NewChannelFromURIWithClientAndController(
    nsIURI *aURI, nsINode *aLoadingNode, nsIPrincipal *aLoadingPrincipal,
    nsIPrincipal *aTriggeringPrincipal,
    const Maybe<ClientInfo> &aLoadingClientInfo,
    const Maybe<ServiceWorkerDescriptor> &aController, uint32_t aSecurityFlags,
    uint32_t aContentPolicyType, nsIChannel **aResult) {
  return NewChannelFromURIWithProxyFlagsInternal(
      aURI,
      nullptr,  // aProxyURI
      0,        // aProxyFlags
      aLoadingNode, aLoadingPrincipal, aTriggeringPrincipal, aLoadingClientInfo,
      aController, aSecurityFlags, aContentPolicyType, aResult);
}

NS_IMETHODIMP
nsIOService::NewChannelFromURIWithLoadInfo(nsIURI *aURI, nsILoadInfo *aLoadInfo,
                                           nsIChannel **result) {
  return NewChannelFromURIWithProxyFlagsInternal(aURI,
                                                 nullptr,  // aProxyURI
                                                 0,        // aProxyFlags
                                                 aLoadInfo, result);
}

nsresult nsIOService::NewChannelFromURIWithProxyFlagsInternal(
    nsIURI *aURI, nsIURI *aProxyURI, uint32_t aProxyFlags,
    nsINode *aLoadingNode, nsIPrincipal *aLoadingPrincipal,
    nsIPrincipal *aTriggeringPrincipal,
    const Maybe<ClientInfo> &aLoadingClientInfo,
    const Maybe<ServiceWorkerDescriptor> &aController, uint32_t aSecurityFlags,
    uint32_t aContentPolicyType, nsIChannel **result) {
  // Ideally all callers of NewChannelFromURIWithProxyFlagsInternal provide
  // the necessary arguments to create a loadinfo.
  //
  // Note, historically this could be called with nullptr aLoadingNode,
  // aLoadingPrincipal, and aTriggeringPrincipal from addons using
  // newChannelFromURIWithProxyFlags().  This code tried to accomodate
  // by not creating a LoadInfo in such cases.  Now that both the legacy
  // addons and that API are gone we could possibly require always creating a
  // LoadInfo here.  See bug 1432205.
  nsCOMPtr<nsILoadInfo> loadInfo;

  // TYPE_DOCUMENT loads don't require a loadingNode or principal, but other
  // types do.
  if (aLoadingNode || aLoadingPrincipal ||
      aContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT) {
    loadInfo = new LoadInfo(aLoadingPrincipal, aTriggeringPrincipal,
                            aLoadingNode, aSecurityFlags, aContentPolicyType,
                            aLoadingClientInfo, aController);
  }
  MOZ_ASSERT(loadInfo, "Please pass security info when creating a channel");
  return NewChannelFromURIWithProxyFlagsInternal(aURI, aProxyURI, aProxyFlags,
                                                 loadInfo, result);
}

nsresult nsIOService::NewChannelFromURIWithProxyFlagsInternal(
    nsIURI *aURI, nsIURI *aProxyURI, uint32_t aProxyFlags,
    nsILoadInfo *aLoadInfo, nsIChannel **result) {
  nsresult rv;
  NS_ENSURE_ARG_POINTER(aURI);

  nsAutoCString scheme;
  rv = aURI->GetScheme(scheme);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIProtocolHandler> handler;
  rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  if (NS_FAILED(rv)) return rv;

  uint32_t protoFlags;
  rv = handler->DoGetProtocolFlags(aURI, &protoFlags);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIChannel> channel;
  nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler);
  if (pph) {
    rv = pph->NewProxiedChannel(aURI, nullptr, aProxyFlags, aProxyURI,
                                aLoadInfo, getter_AddRefs(channel));
  } else {
    rv = handler->NewChannel(aURI, aLoadInfo, getter_AddRefs(channel));
  }
  NS_ENSURE_SUCCESS(rv, rv);

  // Make sure that all the individual protocolhandlers attach a loadInfo.
  if (aLoadInfo) {
    // make sure we have the same instance of loadInfo on the newly created
    // channel
    nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
    if (aLoadInfo != loadInfo) {
      MOZ_ASSERT(false, "newly created channel must have a loadinfo attached");
      return NS_ERROR_UNEXPECTED;
    }

    // If we're sandboxed, make sure to clear any owner the channel
    // might already have.
    if (loadInfo->GetLoadingSandboxed()) {
      channel->SetOwner(nullptr);
    }
  }

  // Some extensions override the http protocol handler and provide their own
  // implementation. The channels returned from that implementation doesn't
  // seem to always implement the nsIUploadChannel2 interface, presumably
  // because it's a new interface.
  // Eventually we should remove this and simply require that http channels
  // implement the new interface.
  // See bug 529041
  if (!gHasWarnedUploadChannel2 && scheme.EqualsLiteral("http")) {
    nsCOMPtr<nsIUploadChannel2> uploadChannel2 = do_QueryInterface(channel);
    if (!uploadChannel2) {
      nsCOMPtr<nsIConsoleService> consoleService =
          do_GetService(NS_CONSOLESERVICE_CONTRACTID);
      if (consoleService) {
        consoleService->LogStringMessage(
            u"Http channel implementation "
            "doesn't support nsIUploadChannel2. An extension has "
            "supplied a non-functional http protocol handler. This will "
            "break behavior and in future releases not work at all.");
      }
      gHasWarnedUploadChannel2 = true;
    }
  }

  channel.forget(result);
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::NewChannelFromURIWithProxyFlags(
    nsIURI *aURI, nsIURI *aProxyURI, uint32_t aProxyFlags,
    nsINode *aLoadingNode, nsIPrincipal *aLoadingPrincipal,
    nsIPrincipal *aTriggeringPrincipal, uint32_t aSecurityFlags,
    uint32_t aContentPolicyType, nsIChannel **result) {
  return NewChannelFromURIWithProxyFlagsInternal(
      aURI, aProxyURI, aProxyFlags, aLoadingNode, aLoadingPrincipal,
      aTriggeringPrincipal, Maybe<ClientInfo>(),
      Maybe<ServiceWorkerDescriptor>(), aSecurityFlags, aContentPolicyType,
      result);
}

NS_IMETHODIMP
nsIOService::NewChannel(const nsACString &aSpec, const char *aCharset,
                        nsIURI *aBaseURI, nsINode *aLoadingNode,
                        nsIPrincipal *aLoadingPrincipal,
                        nsIPrincipal *aTriggeringPrincipal,
                        uint32_t aSecurityFlags, uint32_t aContentPolicyType,
                        nsIChannel **result) {
  nsresult rv;
  nsCOMPtr<nsIURI> uri;
  rv = NewURI(aSpec, aCharset, aBaseURI, getter_AddRefs(uri));
  if (NS_FAILED(rv)) return rv;

  return NewChannelFromURI(uri, aLoadingNode, aLoadingPrincipal,
                           aTriggeringPrincipal, aSecurityFlags,
                           aContentPolicyType, result);
}

bool nsIOService::IsLinkUp() {
  InitializeNetworkLinkService();

  if (!mNetworkLinkService) {
    // We cannot decide, assume the link is up
    return true;
  }

  bool isLinkUp;
  nsresult rv;
  rv = mNetworkLinkService->GetIsLinkUp(&isLinkUp);
  if (NS_FAILED(rv)) {
    return true;
  }

  return isLinkUp;
}

NS_IMETHODIMP
nsIOService::GetOffline(bool *offline) {
  if (mOfflineMirrorsConnectivity) {
    *offline = mOffline || !mConnectivity;
  } else {
    *offline = mOffline;
  }
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::SetOffline(bool offline) {
  LOG(("nsIOService::SetOffline offline=%d\n", offline));
  // When someone wants to go online (!offline) after we got XPCOM shutdown
  // throw ERROR_NOT_AVAILABLE to prevent return to online state.
  if ((mShutdown || mOfflineForProfileChange) && !offline)
    return NS_ERROR_NOT_AVAILABLE;

  // SetOffline() may re-enter while it's shutting down services.
  // If that happens, save the most recent value and it will be
  // processed when the first SetOffline() call is done bringing
  // down the service.
  mSetOfflineValue = offline;
  if (mSettingOffline) {
    return NS_OK;
  }

  mSettingOffline = true;

  nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();

  NS_ASSERTION(observerService, "The observer service should not be null");

  if (XRE_IsParentProcess()) {
    if (observerService) {
      (void)observerService->NotifyObservers(nullptr,
                                             NS_IPC_IOSERVICE_SET_OFFLINE_TOPIC,
                                             offline ? u"true" : u"false");
    }
  }

  nsIIOService *subject = static_cast<nsIIOService *>(this);
  while (mSetOfflineValue != mOffline) {
    offline = mSetOfflineValue;

    if (offline && !mOffline) {
      mOffline = true;  // indicate we're trying to shutdown

      // don't care if notifications fail
      if (observerService)
        observerService->NotifyObservers(subject,
                                         NS_IOSERVICE_GOING_OFFLINE_TOPIC,
                                         u"" NS_IOSERVICE_OFFLINE);

      if (mSocketTransportService) mSocketTransportService->SetOffline(true);

      mLastOfflineStateChange = PR_IntervalNow();
      if (observerService)
        observerService->NotifyObservers(subject,
                                         NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
                                         u"" NS_IOSERVICE_OFFLINE);
    } else if (!offline && mOffline) {
      // go online
      InitializeSocketTransportService();
      mOffline = false;  // indicate success only AFTER we've
                         // brought up the services

      mLastOfflineStateChange = PR_IntervalNow();
      // don't care if notification fails
      // Only send the ONLINE notification if there is connectivity
      if (observerService && mConnectivity) {
        observerService->NotifyObservers(subject,
                                         NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
                                         (u"" NS_IOSERVICE_ONLINE));
      }
    }
  }

  // Don't notify here, as the above notifications (if used) suffice.
  if ((mShutdown || mOfflineForProfileChange) && mOffline) {
    if (mSocketTransportService) {
      DebugOnly<nsresult> rv = mSocketTransportService->Shutdown(mShutdown);
      NS_ASSERTION(NS_SUCCEEDED(rv),
                   "socket transport service shutdown failed");
    }
  }

  mSettingOffline = false;

  return NS_OK;
}

NS_IMETHODIMP
nsIOService::GetConnectivity(bool *aConnectivity) {
  *aConnectivity = mConnectivity;
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::SetConnectivity(bool aConnectivity) {
  LOG(("nsIOService::SetConnectivity aConnectivity=%d\n", aConnectivity));
  // This should only be called from ContentChild to pass the connectivity
  // value from the chrome process to the content process.
  if (XRE_IsParentProcess()) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  return SetConnectivityInternal(aConnectivity);
}

nsresult nsIOService::SetConnectivityInternal(bool aConnectivity) {
  LOG(("nsIOService::SetConnectivityInternal aConnectivity=%d\n",
       aConnectivity));
  if (mConnectivity == aConnectivity) {
    // Nothing to do here.
    return NS_OK;
  }
  mConnectivity = aConnectivity;

  // This is used for PR_Connect PR_Close telemetry so it is important that
  // we have statistic about network change event even if we are offline.
  mLastConnectivityChange = PR_IntervalNow();

  if (mCaptivePortalService) {
    if (aConnectivity && gCaptivePortalEnabled) {
      // This will also trigger a captive portal check for the new network
      static_cast<CaptivePortalService *>(mCaptivePortalService.get())->Start();
    } else {
      static_cast<CaptivePortalService *>(mCaptivePortalService.get())->Stop();
    }
  }

  nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
  if (!observerService) {
    return NS_OK;
  }
  // This notification sends the connectivity to the child processes
  if (XRE_IsParentProcess()) {
    observerService->NotifyObservers(nullptr,
                                     NS_IPC_IOSERVICE_SET_CONNECTIVITY_TOPIC,
                                     aConnectivity ? u"true" : u"false");
  }

  if (mOffline) {
    // We don't need to send any notifications if we're offline
    return NS_OK;
  }

  if (aConnectivity) {
    // If we were previously offline due to connectivity=false,
    // send the ONLINE notification
    observerService->NotifyObservers(static_cast<nsIIOService *>(this),
                                     NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
                                     (u"" NS_IOSERVICE_ONLINE));
  } else {
    // If we were previously online and lost connectivity
    // send the OFFLINE notification
    observerService->NotifyObservers(static_cast<nsIIOService *>(this),
                                     NS_IOSERVICE_GOING_OFFLINE_TOPIC,
                                     u"" NS_IOSERVICE_OFFLINE);
    observerService->NotifyObservers(static_cast<nsIIOService *>(this),
                                     NS_IOSERVICE_OFFLINE_STATUS_TOPIC,
                                     u"" NS_IOSERVICE_OFFLINE);
  }
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::AllowPort(int32_t inPort, const char *scheme, bool *_retval) {
  int16_t port = inPort;
  if (port == -1) {
    *_retval = true;
    return NS_OK;
  }

  if (port == 0) {
    *_retval = false;
    return NS_OK;
  }

  // first check to see if the port is in our blacklist:
  int32_t badPortListCnt = mRestrictedPortList.Length();
  for (int i = 0; i < badPortListCnt; i++) {
    if (port == mRestrictedPortList[i]) {
      *_retval = false;

      // check to see if the protocol wants to override
      if (!scheme) return NS_OK;

      nsCOMPtr<nsIProtocolHandler> handler;
      nsresult rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
      if (NS_FAILED(rv)) return rv;

      // let the protocol handler decide
      return handler->AllowPort(port, scheme, _retval);
    }
  }

  *_retval = true;
  return NS_OK;
}

////////////////////////////////////////////////////////////////////////////////

void nsIOService::PrefsChanged(const char *pref) {
  // Look for extra ports to block
  if (!pref || strcmp(pref, PORT_PREF("banned")) == 0)
    ParsePortList(PORT_PREF("banned"), false);

  // ...as well as previous blocks to remove.
  if (!pref || strcmp(pref, PORT_PREF("banned.override")) == 0)
    ParsePortList(PORT_PREF("banned.override"), true);

  if (!pref || strcmp(pref, MANAGE_OFFLINE_STATUS_PREF) == 0) {
    bool manage;
    if (mNetworkLinkServiceInitialized &&
        NS_SUCCEEDED(
            Preferences::GetBool(MANAGE_OFFLINE_STATUS_PREF, &manage))) {
      LOG(("nsIOService::PrefsChanged ManageOfflineStatus manage=%d\n",
           manage));
      SetManageOfflineStatus(manage);
    }
  }

  if (!pref || strcmp(pref, NECKO_BUFFER_CACHE_COUNT_PREF) == 0) {
    int32_t count;
    if (NS_SUCCEEDED(
            Preferences::GetInt(NECKO_BUFFER_CACHE_COUNT_PREF, &count)))
      /* check for bogus values and default if we find such a value */
      if (count > 0) gDefaultSegmentCount = count;
  }

  if (!pref || strcmp(pref, NECKO_BUFFER_CACHE_SIZE_PREF) == 0) {
    int32_t size;
    if (NS_SUCCEEDED(Preferences::GetInt(NECKO_BUFFER_CACHE_SIZE_PREF, &size)))
      /* check for bogus values and default if we find such a value
       * the upper limit here is arbitrary. having a 1mb segment size
       * is pretty crazy.  if you remove this, consider adding some
       * integer rollover test.
       */
      if (size > 0 && size < 1024 * 1024) gDefaultSegmentSize = size;
    NS_WARNING_ASSERTION(!(size & (size - 1)),
                         "network segment size is not a power of 2!");
  }

  if (!pref || strcmp(pref, NETWORK_NOTIFY_CHANGED_PREF) == 0) {
    bool allow;
    nsresult rv = Preferences::GetBool(NETWORK_NOTIFY_CHANGED_PREF, &allow);
    if (NS_SUCCEEDED(rv)) {
      mNetworkNotifyChanged = allow;
    }
  }

  if (!pref || strcmp(pref, NETWORK_CAPTIVE_PORTAL_PREF) == 0) {
    nsresult rv = Preferences::GetBool(NETWORK_CAPTIVE_PORTAL_PREF,
                                       &gCaptivePortalEnabled);
    if (NS_SUCCEEDED(rv) && mCaptivePortalService) {
      if (gCaptivePortalEnabled) {
        static_cast<CaptivePortalService *>(mCaptivePortalService.get())
            ->Start();
      } else {
        static_cast<CaptivePortalService *>(mCaptivePortalService.get())
            ->Stop();
      }
    }
  }
}

void nsIOService::ParsePortList(const char *pref, bool remove) {
  nsAutoCString portList;

  // Get a pref string and chop it up into a list of ports.
  Preferences::GetCString(pref, portList);
  if (!portList.IsVoid()) {
    nsTArray<nsCString> portListArray;
    ParseString(portList, ',', portListArray);
    uint32_t index;
    for (index = 0; index < portListArray.Length(); index++) {
      portListArray[index].StripWhitespace();
      int32_t portBegin, portEnd;

      if (PR_sscanf(portListArray[index].get(), "%d-%d", &portBegin,
                    &portEnd) == 2) {
        if ((portBegin < 65536) && (portEnd < 65536)) {
          int32_t curPort;
          if (remove) {
            for (curPort = portBegin; curPort <= portEnd; curPort++)
              mRestrictedPortList.RemoveElement(curPort);
          } else {
            for (curPort = portBegin; curPort <= portEnd; curPort++)
              mRestrictedPortList.AppendElement(curPort);
          }
        }
      } else {
        nsresult aErrorCode;
        int32_t port = portListArray[index].ToInteger(&aErrorCode);
        if (NS_SUCCEEDED(aErrorCode) && port < 65536) {
          if (remove)
            mRestrictedPortList.RemoveElement(port);
          else
            mRestrictedPortList.AppendElement(port);
        }
      }
    }
  }
}

class nsWakeupNotifier : public Runnable {
 public:
  explicit nsWakeupNotifier(nsIIOServiceInternal *ioService)
      : Runnable("net::nsWakeupNotifier"), mIOService(ioService) {}

  NS_IMETHOD Run() override { return mIOService->NotifyWakeup(); }

 private:
  virtual ~nsWakeupNotifier() = default;
  nsCOMPtr<nsIIOServiceInternal> mIOService;
};

NS_IMETHODIMP
nsIOService::NotifyWakeup() {
  nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();

  NS_ASSERTION(observerService, "The observer service should not be null");

  if (observerService && mNetworkNotifyChanged) {
    (void)observerService->NotifyObservers(nullptr, NS_NETWORK_LINK_TOPIC,
                                           (u"" NS_NETWORK_LINK_DATA_CHANGED));
  }

  RecheckCaptivePortal();

  return NS_OK;
}

void nsIOService::SetHttpHandlerAlreadyShutingDown() {
  if (!mShutdown && !mOfflineForProfileChange) {
    mNetTearingDownStarted = PR_IntervalNow();
    mHttpHandlerAlreadyShutingDown = true;
  }
}

// nsIObserver interface
NS_IMETHODIMP
nsIOService::Observe(nsISupports *subject, const char *topic,
                     const char16_t *data) {
  if (!strcmp(topic, kProfileChangeNetTeardownTopic)) {
    if (!mHttpHandlerAlreadyShutingDown) {
      mNetTearingDownStarted = PR_IntervalNow();
    }
    mHttpHandlerAlreadyShutingDown = false;
    if (!mOffline) {
      mOfflineForProfileChange = true;
      SetOffline(true);
    }
  } else if (!strcmp(topic, kProfileChangeNetRestoreTopic)) {
    if (mOfflineForProfileChange) {
      mOfflineForProfileChange = false;
      SetOffline(false);
    }
  } else if (!strcmp(topic, kProfileDoChange)) {
    if (!data) {
      return NS_OK;
    }
    if (NS_LITERAL_STRING("startup").Equals(data)) {
      // Lazy initialization of network link service (see bug 620472)
      InitializeNetworkLinkService();
      // Set up the initilization flag regardless the actuall result.
      // If we fail here, we will fail always on.
      mNetworkLinkServiceInitialized = true;

      // And now reflect the preference setting
      PrefsChanged(MANAGE_OFFLINE_STATUS_PREF);

      // Bug 870460 - Read cookie database at an early-as-possible time
      // off main thread. Hence, we have more chance to finish db query
      // before something calls into the cookie service.
      nsCOMPtr<nsISupports> cookieServ =
          do_GetService(NS_COOKIESERVICE_CONTRACTID);
    } else if (NS_LITERAL_STRING("xpcshell-do-get-profile").Equals(data)) {
      // xpcshell doesn't read user profile.
      LaunchSocketProcess();
    }
  } else if (!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
    // Remember we passed XPCOM shutdown notification to prevent any
    // changes of the offline status from now. We must not allow going
    // online after this point.
    mShutdown = true;

    if (!mHttpHandlerAlreadyShutingDown && !mOfflineForProfileChange) {
      mNetTearingDownStarted = PR_IntervalNow();
    }
    mHttpHandlerAlreadyShutingDown = false;

    SetOffline(true);

    if (mCaptivePortalService) {
      static_cast<CaptivePortalService *>(mCaptivePortalService.get())->Stop();
      mCaptivePortalService = nullptr;
    }

    DestroySocketProcess();
  } else if (!strcmp(topic, NS_NETWORK_LINK_TOPIC)) {
    OnNetworkLinkEvent(NS_ConvertUTF16toUTF8(data).get());
  } else if (!strcmp(topic, NS_WIDGET_WAKE_OBSERVER_TOPIC)) {
    // coming back alive from sleep
    // this indirection brought to you by:
    // https://bugzilla.mozilla.org/show_bug.cgi?id=1152048#c19
    nsCOMPtr<nsIRunnable> wakeupNotifier = new nsWakeupNotifier(this);
    NS_DispatchToMainThread(wakeupNotifier);
  } else if (!strcmp(topic, NS_PREFSERVICE_READ_TOPIC_ID)) {
    // Launch socket process after we load user's pref. This is to make sure
    // that socket process can get the latest prefs.
    LaunchSocketProcess();
  }

  return NS_OK;
}

// nsINetUtil interface
NS_IMETHODIMP
nsIOService::ParseRequestContentType(const nsACString &aTypeHeader,
                                     nsACString &aCharset, bool *aHadCharset,
                                     nsACString &aContentType) {
  net_ParseRequestContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
  return NS_OK;
}

// nsINetUtil interface
NS_IMETHODIMP
nsIOService::ParseResponseContentType(const nsACString &aTypeHeader,
                                      nsACString &aCharset, bool *aHadCharset,
                                      nsACString &aContentType) {
  net_ParseContentType(aTypeHeader, aContentType, aCharset, aHadCharset);
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::ProtocolHasFlags(nsIURI *uri, uint32_t flags, bool *result) {
  NS_ENSURE_ARG(uri);

  *result = false;
  nsAutoCString scheme;
  nsresult rv = uri->GetScheme(scheme);
  NS_ENSURE_SUCCESS(rv, rv);

  // Grab the protocol flags from the URI.
  uint32_t protocolFlags;
  nsCOMPtr<nsIProtocolHandler> handler;
  rv = GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = handler->DoGetProtocolFlags(uri, &protocolFlags);
  NS_ENSURE_SUCCESS(rv, rv);

  *result = (protocolFlags & flags) == flags;
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::URIChainHasFlags(nsIURI *uri, uint32_t flags, bool *result) {
  nsresult rv = ProtocolHasFlags(uri, flags, result);
  NS_ENSURE_SUCCESS(rv, rv);

  if (*result) {
    return rv;
  }

  // Dig deeper into the chain.  Note that this is not a do/while loop to
  // avoid the extra addref/release on |uri| in the common (non-nested) case.
  nsCOMPtr<nsINestedURI> nestedURI = do_QueryInterface(uri);
  while (nestedURI) {
    nsCOMPtr<nsIURI> innerURI;
    rv = nestedURI->GetInnerURI(getter_AddRefs(innerURI));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = ProtocolHasFlags(innerURI, flags, result);

    if (*result) {
      return rv;
    }

    nestedURI = do_QueryInterface(innerURI);
  }

  return rv;
}

NS_IMETHODIMP
nsIOService::SetManageOfflineStatus(bool aManage) {
  LOG(("nsIOService::SetManageOfflineStatus aManage=%d\n", aManage));
  mManageLinkStatus = aManage;

  // When detection is not activated, the default connectivity state is true.
  if (!mManageLinkStatus) {
    SetConnectivityInternal(true);
    return NS_OK;
  }

  InitializeNetworkLinkService();
  // If the NetworkLinkService is already initialized, it does not call
  // OnNetworkLinkEvent. This is needed, when mManageLinkStatus goes from
  // false to true.
  OnNetworkLinkEvent(NS_NETWORK_LINK_DATA_UNKNOWN);
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::GetManageOfflineStatus(bool *aManage) {
  *aManage = mManageLinkStatus;
  return NS_OK;
}

// input argument 'data' is already UTF8'ed
nsresult nsIOService::OnNetworkLinkEvent(const char *data) {
  if (IsNeckoChild() || IsSocketProcessChild()) {
    // There is nothing IO service could do on the child process
    // with this at the moment.  Feel free to add functionality
    // here at will, though.
    return NS_OK;
  }

  if (mShutdown) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  nsCString dataAsString(data);
  for (auto *cp : mozilla::dom::ContentParent::AllProcesses(
           mozilla::dom::ContentParent::eLive)) {
    PNeckoParent *neckoParent = SingleManagedOrNull(cp->ManagedPNeckoParent());
    if (!neckoParent) {
      continue;
    }
    Unused << neckoParent->SendNetworkChangeNotification(dataAsString);
  }

  LOG(("nsIOService::OnNetworkLinkEvent data:%s\n", data));
  if (!mNetworkLinkService) {
    return NS_ERROR_FAILURE;
  }

  if (!mManageLinkStatus) {
    LOG(("nsIOService::OnNetworkLinkEvent mManageLinkStatus=false\n"));
    return NS_OK;
  }

  bool isUp = true;
  if (!strcmp(data, NS_NETWORK_LINK_DATA_CHANGED)) {
    mLastNetworkLinkChange = PR_IntervalNow();
    // CHANGED means UP/DOWN didn't change
    // but the status of the captive portal may have changed.
    RecheckCaptivePortal();
    return NS_OK;
  }
  if (!strcmp(data, NS_NETWORK_LINK_DATA_DOWN)) {
    isUp = false;
  } else if (!strcmp(data, NS_NETWORK_LINK_DATA_UP)) {
    isUp = true;
  } else if (!strcmp(data, NS_NETWORK_LINK_DATA_UNKNOWN)) {
    nsresult rv = mNetworkLinkService->GetIsLinkUp(&isUp);
    NS_ENSURE_SUCCESS(rv, rv);
  } else {
    NS_WARNING("Unhandled network event!");
    return NS_OK;
  }

  return SetConnectivityInternal(isUp);
}

NS_IMETHODIMP
nsIOService::EscapeString(const nsACString &aString, uint32_t aEscapeType,
                          nsACString &aResult) {
  NS_ENSURE_ARG_MAX(aEscapeType, 4);

  nsAutoCString stringCopy(aString);
  nsCString result;

  if (!NS_Escape(stringCopy, result, (nsEscapeMask)aEscapeType))
    return NS_ERROR_OUT_OF_MEMORY;

  aResult.Assign(result);

  return NS_OK;
}

NS_IMETHODIMP
nsIOService::EscapeURL(const nsACString &aStr, uint32_t aFlags,
                       nsACString &aResult) {
  aResult.Truncate();
  NS_EscapeURL(aStr.BeginReading(), aStr.Length(), aFlags | esc_AlwaysCopy,
               aResult);
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::UnescapeString(const nsACString &aStr, uint32_t aFlags,
                            nsACString &aResult) {
  aResult.Truncate();
  NS_UnescapeURL(aStr.BeginReading(), aStr.Length(), aFlags | esc_AlwaysCopy,
                 aResult);
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::ExtractCharsetFromContentType(const nsACString &aTypeHeader,
                                           nsACString &aCharset,
                                           int32_t *aCharsetStart,
                                           int32_t *aCharsetEnd,
                                           bool *aHadCharset) {
  nsAutoCString ignored;
  net_ParseContentType(aTypeHeader, ignored, aCharset, aHadCharset,
                       aCharsetStart, aCharsetEnd);
  if (*aHadCharset && *aCharsetStart == *aCharsetEnd) {
    *aHadCharset = false;
  }
  return NS_OK;
}

// parse policyString to policy enum value (see ReferrerPolicy.h)
NS_IMETHODIMP
nsIOService::ParseAttributePolicyString(const nsAString &policyString,
                                        uint32_t *outPolicyEnum) {
  NS_ENSURE_ARG(outPolicyEnum);
  *outPolicyEnum = (uint32_t)AttributeReferrerPolicyFromString(policyString);
  return NS_OK;
}

NS_IMETHODIMP
nsIOService::GetReferrerPolicyString(uint32_t aPolicy, nsACString &aResult) {
  if (aPolicy >= ArrayLength(kReferrerPolicyString)) {
    aResult.AssignLiteral("unknown");
    return NS_ERROR_INVALID_ARG;
  }

  aResult.AssignASCII(
      ReferrerPolicyToString(static_cast<ReferrerPolicy>(aPolicy)));
  return NS_OK;
}

// nsISpeculativeConnect
class IOServiceProxyCallback final : public nsIProtocolProxyCallback {
  ~IOServiceProxyCallback() = default;

 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIPROTOCOLPROXYCALLBACK

  IOServiceProxyCallback(nsIInterfaceRequestor *aCallbacks,
                         nsIOService *aIOService)
      : mCallbacks(aCallbacks), mIOService(aIOService) {}

 private:
  RefPtr<nsIInterfaceRequestor> mCallbacks;
  RefPtr<nsIOService> mIOService;
};

NS_IMPL_ISUPPORTS(IOServiceProxyCallback, nsIProtocolProxyCallback)

NS_IMETHODIMP
IOServiceProxyCallback::OnProxyAvailable(nsICancelable *request,
                                         nsIChannel *channel, nsIProxyInfo *pi,
                                         nsresult status) {
  // Checking proxy status for speculative connect
  nsAutoCString type;
  if (NS_SUCCEEDED(status) && pi && NS_SUCCEEDED(pi->GetType(type)) &&
      !type.EqualsLiteral("direct")) {
    // proxies dont do speculative connect
    return NS_OK;
  }

  nsCOMPtr<nsIURI> uri;
  nsresult rv = channel->GetURI(getter_AddRefs(uri));
  if (NS_FAILED(rv)) {
    return NS_OK;
  }

  nsAutoCString scheme;
  rv = uri->GetScheme(scheme);
  if (NS_FAILED(rv)) return NS_OK;

  nsCOMPtr<nsIProtocolHandler> handler;
  rv = mIOService->GetProtocolHandler(scheme.get(), getter_AddRefs(handler));
  if (NS_FAILED(rv)) return NS_OK;

  nsCOMPtr<nsISpeculativeConnect> speculativeHandler =
      do_QueryInterface(handler);
  if (!speculativeHandler) return NS_OK;

  nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
  nsCOMPtr<nsIPrincipal> principal = loadInfo->LoadingPrincipal();

  nsLoadFlags loadFlags = 0;
  channel->GetLoadFlags(&loadFlags);
  if (loadFlags & nsIRequest::LOAD_ANONYMOUS) {
    speculativeHandler->SpeculativeAnonymousConnect(uri, principal, mCallbacks);
  } else {
    speculativeHandler->SpeculativeConnect(uri, principal, mCallbacks);
  }

  return NS_OK;
}

nsresult nsIOService::SpeculativeConnectInternal(
    nsIURI *aURI, nsIPrincipal *aPrincipal, nsIInterfaceRequestor *aCallbacks,
    bool aAnonymous) {
  NS_ENSURE_ARG(aURI);

  bool isHTTP, isHTTPS;
  if (!(NS_SUCCEEDED(aURI->SchemeIs("http", &isHTTP)) && isHTTP) &&
      !(NS_SUCCEEDED(aURI->SchemeIs("https", &isHTTPS)) && isHTTPS)) {
    // We don't speculatively connect to non-HTTP[S] URIs.
    return NS_OK;
  }

  if (IsNeckoChild()) {
    ipc::URIParams params;
    SerializeURI(aURI, params);
    gNeckoChild->SendSpeculativeConnect(params, IPC::Principal(aPrincipal),
                                        aAnonymous);
    return NS_OK;
  }

  // Check for proxy information. If there is a proxy configured then a
  // speculative connect should not be performed because the potential
  // reward is slim with tcp peers closely located to the browser.
  nsresult rv;
  nsCOMPtr<nsIProtocolProxyService> pps =
      do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIPrincipal> loadingPrincipal = aPrincipal;

  MOZ_ASSERT(aPrincipal, "We expect passing a principal here.");

  // dummy channel used to create a TCP connection.
  // we perform security checks on the *real* channel, responsible
  // for any network loads. this real channel just checks the TCP
  // pool if there is an available connection created by the
  // channel we create underneath - hence it's safe to use
  // the systemPrincipal as the loadingPrincipal for this channel.
  nsCOMPtr<nsIChannel> channel;
  rv = NewChannelFromURI(aURI,
                         nullptr,  // aLoadingNode,
                         loadingPrincipal,
                         nullptr,  // aTriggeringPrincipal,
                         nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                         nsIContentPolicy::TYPE_SPECULATIVE,
                         getter_AddRefs(channel));
  NS_ENSURE_SUCCESS(rv, rv);

  if (aAnonymous) {
    nsLoadFlags loadFlags = 0;
    channel->GetLoadFlags(&loadFlags);
    loadFlags |= nsIRequest::LOAD_ANONYMOUS;
    channel->SetLoadFlags(loadFlags);
  }

  nsCOMPtr<nsICancelable> cancelable;
  RefPtr<IOServiceProxyCallback> callback =
      new IOServiceProxyCallback(aCallbacks, this);
  nsCOMPtr<nsIProtocolProxyService2> pps2 = do_QueryInterface(pps);
  if (pps2) {
    return pps2->AsyncResolve2(channel, 0, callback, nullptr,
                               getter_AddRefs(cancelable));
  }
  return pps->AsyncResolve(channel, 0, callback, nullptr,
                           getter_AddRefs(cancelable));
}

NS_IMETHODIMP
nsIOService::SpeculativeConnect(nsIURI *aURI, nsIPrincipal *aPrincipal,
                                nsIInterfaceRequestor *aCallbacks) {
  return SpeculativeConnectInternal(aURI, aPrincipal, aCallbacks, false);
}

NS_IMETHODIMP
nsIOService::SpeculativeAnonymousConnect(nsIURI *aURI, nsIPrincipal *aPrincipal,
                                         nsIInterfaceRequestor *aCallbacks) {
  return SpeculativeConnectInternal(aURI, aPrincipal, aCallbacks, true);
}

/*static*/
bool nsIOService::IsDataURIUniqueOpaqueOrigin() {
  return sIsDataURIUniqueOpaqueOrigin;
}

/*static*/
bool nsIOService::BlockToplevelDataUriNavigations() {
  return sBlockToplevelDataUriNavigations;
}

/*static*/
bool nsIOService::BlockFTPSubresources() { return sBlockFTPSubresources; }

NS_IMETHODIMP
nsIOService::NotImplemented() { return NS_ERROR_NOT_IMPLEMENTED; }

}  // namespace net
}  // namespace mozilla